On Tue, Jul 23, 2024 at 18:02:53 +1000, Keith Bainbridge wrote:
> From the tab I had used earlier, ran  source .bashrc
> 
> then
>  :/tmp/205.2024   $>    mkcd /tmp/day$DOYR.$YEAR

So you're setting those variables one time inside your .bashrc file?

This is quite bad.  What happens when you have a terminal window that
you open before midnight, and then continue using *after* midnight?
Those variables will still be set to the previous day's values.

Also, why did you start three separate threads for this question?

> So, now question is how can I get cron to 'source .bashrc'    I'm thinking
> add that line to my script?

I would advise against it.  Who knows what kind of silly things your
.bashrc may do that you wouldn't want an automated script to pick up.
Even if you verify that your .bashrc is "cron safe" right now, you
might add something to it a year from now, forgetting that you need
it to remain "cron safe", and accidentally break the script.

Any command that's supposed to act based on the current day will need
to perform its *own* request to fetch the current day from the system
clock.  It cannot rely on an environment variable set some unknown
length of time in the past.

Use the date command or bash's printf %()T inside your bash script to
get the current date.

Moreover, never make *two* calls to the system clock in the same script.
If you need the Julian day number (%j) and also the calendar
day-of-the-month number (%d), don't do this:

    # WRONG
    julian=$(date +%j)
    dom=$(date +%d)

That calls out to the system clock twice, and gets two different values.
If the script is executed right at midnight, you might get two different
days.

Instead, only make *one* call.  There are a couple different ways to do
this.  One is to get all the date(1) fields you need at once, and then
parse them out:

    read -r julian dom < <(date "+%j %d")

Another is to fetch the epoch time value (%s) and then use that value
in all future calls.  With GNU date:

    now=$(date +%s)
    julian=$(date -d "@$now" +%j)
    dom=$(date -d "@$now" +%d)

Or with bash's printf, on Linux or BSD:

    printf -v now '%(%s)T' -1
    printf -v julian '%(%j)T' "$now"
    printf -v dom '%(%d)T' "$now"

(Bash 5.0 added an EPOCHSECONDS variable as well.)

This same concept applies in any programming language you use.  It's not
just a shell script thing, even though I'm showing shell script examples
here.

Reply via email to