views:

117

answers:

4

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

+7  A: 

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
paxdiablo
how about to check if it's weekday? the reverse -- will this workif [ ![ $(date +%u) -gt 5 ]] ; thenfi
vehomzzz
@Andrei, see the update: I'd just use `-lt 6` instead of `-gt 5`.
paxdiablo
arrgh I mean - -if [[ $(date +%u) -lt 6 ]
vehomzzz
+3  A: 
Greg Bacon
+4  A: 
case "$(date +%a)" in 
  Sat|Sun) echo "weekend";;
esac
ghostdog74
+2  A: 

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.

Michael Aaron Safyan
good point. there's also 'long weekends' to consider, for example Bank Holiday Mondays in the UK.this is why it's helpful for people to give some background to their questions, so people answering know what is and isn't relevant...
plusplus
A great point -- In my case, I was referring to Sat and Sunday.
vehomzzz