Eduard Eduard - 5 months ago 14x
Bash Question

Unix - get next saturday using cal command

I need get te next saturday from starting the current date for create a file. For example, on linux:

date +%Y%m%d -d saturday

This return 20160430, the next saturday with current date 4/25/2016. That's I want.

I need the same result (or something like that) on Unix (SunOS 5.10). If I execute the same command, the return is the current date 20160425

There's another way to do that, for example using command cal? I tried but just return the first Saturday. The command:

cal | grep -v 2016 |grep -v Th | head -3 | head -1 | sed 's|^.*\([0-9]\)$|\1|g'

So, there's a way to get the next Saturday, starting from current date, using cal command?

Thanks for help!


You can obtain the day using following command:

cal -s | tail -n +2 | grep `date +%d` | cut -d' ' -f 7

Prints calendar of current month, starting weeks with Sunday, strips the year line, greps the line with today's date and gets its 7-th column, which is your Saturday month day number.

Now here is a little script that calculates the rest.

TODAY=$(date +%d)
DAY=$(cal -s | tail -n +2 | grep ${TODAY} | cut -d' ' -f 7)
MONTH=$(date +%m)
YEAR=$(date +%Y)

if [[ $DAY -lt $TODAY ]]; then
    # Saturday is next month
    let MONTH=MONTH+1
    if [[ $MONTH -eq 13 ]]; then
        # Saturday is next year
        let YEAR=YEAR+1