Shell Script – How to Use If-Else Based on Day of the Week

dateshellshell-scripttest

Problem: I need to check if today is Thursday and perform different actions based on the result of this condition. I tried two different approaches:

Getting the Day Name:

DAYOFWEEK=$(date +"%a")
echo DAYOFWEEK: $DAYOFWEEK
if ["$DAYOFWEEK" == "Thu"]; 
then   
   echo YES
else
    echo NO
fi

Getting the Day Num:

DAYOFWEEK=$(date +"%u")
echo DAYOFWEEK: $DAYOFWEEK

if ["$DAYOFWEEK" == 4]; 
then
   echo YES
else
   echo NO
fi

In both cases, the output is NO, even though it should be YES. What is wrong?

Best Answer

The problem is the missing blank.

The following code will work in shells whose [ builtin command accepts == as an alias for =:

if [ "$DAYOFWEEK" == 4 ];  then    echo YES; else    echo NO; fi

But keep in mind (see help test in bash):

  • == is not officially mentioned, you should use = for string compare
  • -eq is intended for decimal arithmetic tests (won't make a difference here for date +%u but would for date +%d for instance when it comes to comparing 04 and 4 which are numerically the same but lexically different).

I would prefer:

 if [ "${DAYOFWEEK}" -eq 4 ];  then    echo YES; else    echo NO; fi

Generally you should prefer the day number approach, because it has less dependency to the current locale. On my system the output of date +"%a" is today Do.

Related Question