How to check if today is a weekend in bash?

You can use something like:

if [[ $(date +%u) -gt 5 ]]; then echo weekend; fi

date +%u gives you the day of the week from Monday (1) through to Sunday (7). If it’s greater than 5 (Saturday is 6 and Sunday is 7), then it’s the weekend.

So you could put something like this at the top of your script:

if [[ $(date +%u) -gt 5 ]]; then
    echo 'Sorry, you cannot run this program on the weekend.'
    exit
fi

Or the more succinct:

[[ $(date +%u) -gt 5 ]] && { echo "Weekend, not running"; exit; }

To check if it’s a weekday, use the opposite sense (< 6 rather than > 5):

$(date +%u) -lt 6

Leave a Comment