How to check if today is a weekend using bash or even perl?
I want to prevent certain programs to run on a weekend.
Thanks
How to check if today is a weekend using bash or even perl?
I want to prevent certain programs to run on a weekend.
Thanks
You can use:
pax> 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 = 6 or Sunday = 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 today.'
exit
fi
To check if it's a weekday, use:
if [[ $(date +%u) -lt 6 ]] ; then
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.