# Get the date for the last Saturday of a given month

desiredDay=6; year=2012; month=5; n=0; while [ \$(date -d "\$year-\$((month+1))-1 - \$n day" "+%u") -ne \$desiredDay ]; do n=\$((n+1)); done; date -d "\$year-\$((month+1))-1 - \$n day" "+%x"
Choosing your year and month. You only need the gnu date command and bash. desiredDay of the week is (1..7); 1 is Monday. If you want desiredDay of week (0..6); 0 is Sunday `desiredDay=6; year=2012; month=5; n=0; while [ \$(date -d "\$year-\$((month+1))-1 - \$n day" "+%w") -ne \$desiredDay ]; do n=\$((n+1)); done; date -d "\$year-\$((month+1))-1 - \$n day" "+%x"`
Sample Output
`05/26/2012`

0
2012-05-17 12:02:30

## 2 Alternatives + Submit Alt

• If your locale has Monday as the first day of the week, like mine in the UK, change the two \$7 into \$6 Show Sample Output

2
cal 04 2012 | awk '{ \$7 && X=\$7 } END { print X }'
· 2012-05-06 23:43:21
• This is a little trickier than finding the last Sunday, because you know the last Sunday is in the first position of the last line. The trick is to use the NF less than or equal to 7 so it picks up all the lines then grep out any empty lines. Show Sample Output

-2
cal 04 2012 | awk 'NF <= 7 { print \$7 }' | grep -v "^\$" | tail -1
· 2012-05-03 16:57:45

### What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

### What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.