1

I have a script that runs every day. Depending on what day of the week it is, or if tomorrow is the last day of the month, it will move files into different locations. I have omitted the actual functions.

Variables:

TOM=$(TZ=UTC-24 date +%d)
SUNDAY=$(date +%w)

The logic is as below:

    if [ $TOM -eq 1 ]; then
            move_files monthly
    echo EXEUTING END OF MONTH MOVE AND PURGE, NON-DAILY, NON-END-OF-MONTH

    elif [ $SUNDAY -eq 0 ]; then
            move_files weekly
    echo EXECUTING SUNDAY MOVE AND PURGE, NON-DAILY, NON-END-OF-MONTH

    else echo EXECUTING DAILY MOVE AND PURGE NON-SUNDAY, NON-END-OF-MONTH
            move_files daily
    fi

Everything executes properly, however yesterday (Nov. 30th) it did not properly move the files into the monthly directory, which is part of the move_files monthly function. Testing elsewhere, this seems to work fine.

The host I'm running this on is on UTC.

4
  • 3
    Why don't you use date -d tomorrow instead of trying to twist date's arm with unlikely timezones? – xenoid Dec 1 '19 at 18:27
  • Are you using GNU date? – Kusalananda Dec 1 '19 at 18:37
  • I am using GNU date, 8.2.5. – Kahn Dec 1 '19 at 18:46
  • What does date +%d produce today? On my system, it's 01, not 1 (not sure this makes any difference). Has the monthly function ever worked? I use this: if [ `date +%d` = "01" ]. – ajgringo619 Dec 1 '19 at 18:54
2

Putting together some comments above, with GNU date you can check to see if tomorrow is the first day of the month with:

if [[ "$(date -d tomorrow +%d)" == "01" ]]; then
    echo "Tomorrow is the first day of the month"
fi

If you want to know if tomorrow is the last day of the month, you can similarly do:

if [[ "$(date -d "2 days" +%d)" == "01" ]]; then
    echo "Tomorrow is the last day of the month"
fi
0

Your issue could possibly be related to your local timezone not actually being UTC after all. The best way to get an offset time with GNU date is to use its -d option with an argument describing the date you'd like to use as reference instead of "now" (as shown in Andy's answer). If you additionally want to get the response back in UTC from GNU date, use its -u option.

Without using GNU date, in bash release 4.3+:

#!/bin/bash

# Unix timestamp "now"
printf -v now '%(%s)T'    # append "-1" as argument to get it working in bash 4.2

# Today's weekday, 1-7, 1=Monday
printf -v today_day '%(%u)T' "$now"

# Tomorrow's date, 1-31
printf -v tomorrow_date '%(%e)T' "$(( now + 24*60*60 ))"

if [ "$tomorrow_date" -eq 1 ]; then
    echo Today is the last day of the month
elif [ "$today_day" -eq 7 ]; then
    echo Today is Sunday
else
    echo Today is some other day
fi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.