How to check if today is a weekend in bash? How to check if today is a weekend in bash? bash bash

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.'    exitfi

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


case "$(date +%a)" in   Sat|Sun) echo "weekend";;esac


This is actually a surprisingly difficult problem, because who is to say that "weekend" means Saturday and Sunday... what constitutes "the weekend" can actually vary across cultures (e.g. in Israel, people work on Sunday and have Friday off). While you can get the date with the date command, you will need to store some additional data indicating what constitutes the weekend for each locale if you are to implement this in a way that works for all users. If you target only one country, then the solution posed in the other answers will work... but it is always good to keep in mind the assumptions being made here.