How do I use an If-Else query based on the day of the week?

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.


Don't overlook case which is often a better way to do this kind of things:

Also beware that the output of date +%a is locale-dependent, so if you expect the English names, your script will stop working when invoked by a French or Korean user for instance.

case $(LC_ALL=C date +%a) in
   (Mon) echo first day of the week;;
   (Thu) do-something;;
   (Sat|Sun) echo week-end;;
   (*) echo any other day;; # last ;; not necessary but doesn't harm
esac

Note that above is one of the rare cases where that $(...) doesn't need to be quoted (though quotes won't harm. Same as in var="$(...)").