How do I compare the day of the week?

13,770

Try this :

echo "Today's date is: $(date)"
day=$(date +"%u")

if ((day > 5)); then
   echo "WEEKEND"        
else
   echo "WORKING DAY"
fi

I use (( )) bash arithmetic

Or less readable :

echo "Today's date is: $(date)"
day=$(date +"%u")

if [[ day -gt 5 ]]; then
   echo "WEEKEND"        
else
   echo "WORKING DAY"
fi
Share:
13,770

Related videos on Youtube

Ensz
Author by

Ensz

Updated on September 18, 2022

Comments

  • Ensz
    Ensz over 1 year

    I'm trying write a script which shows right statement based on which day of the week it is. Two examples:

    1. If today is 4th day of the week. echo Today is a working day.
    2. If today is 6th day of the week. echo Today is a weekend.

    I wrote this however it doesn't work

    echo Hello!
    echo Today's date is: date
    DAY=$(date +"%u")
    if [ "${DZIEN}" -ge 1 && "${DZIEN}" -le 5 ]
    then 
       echo WORKING DAY;
    else
       echo WEEKEND;
    fi
    
    • Admin
      Admin over 7 years
      you set DAY, then check DZIEN... pick one. And perhaps try -a instead &&.
    • Admin
      Admin over 7 years
      You need [..] && [..] or [[.. && ..]] - why don't you google for shell multiple conditions in if ?? It's much shorter to type than all the above...
    • Admin
      Admin over 7 years
      @frostschutz I made a mistake in copying variable name.
    • Admin
      Admin over 7 years
      @don_crissti I have to do this in that way, this is a task from the teacher :/ Thanks for help, now it's working.
  • Michael Hoffmann
    Michael Hoffmann about 5 years
    Why does this work? What is %u?
  • Janek Bogucki
    Janek Bogucki over 4 years
    From man date, % is the format specifier for day of week: %u day of week (1..7); 1 is Monday