Shell – Get date of next Saturday from a given date

dateshell-script

I want the date of the coming Saturday after a given date.
For example, for $date1="30-AUG-2015", I want the result 05-SEP-2015.

I have tried all the commands below with no success:

samba@samba:~$ date1="30-AUG-2015"
samba@samba:~$ date2=$(date --date='"$date1" +next Saturday')
date: invalid date ‘"$date1" +next Saturday’

samba@samba:~$ date1="30-AUG-2015"
samba@samba:~$ date2=$(date --date1='next Saturday')
date: unrecognized option '--date1=next Saturday'
Try 'date --help' for more information.

samba@samba:~$ date1="30-AUG-2015"
samba@samba:~$ date -d "$date1 next saturday"
Sun Aug 30 00:00:00 IST 2015
samba@samba:~$ $date1 -d "next saturday"
30-AUG-2015: command not found

Best Answer

I highly recommend dateutils for things like this. (yum install dateutils on Fedora 21+ or CentOS/RHEL 7 with EPEL.). On Debian-based systems, the package is also called dateutils but the commands are prefixed with dateutils. to disambiguate some of them with commands with the same names in unrelated packages (replace dateround with dateutils.dround below).

Then, just do:

dateround today sunday

You can use "today" or replace with an actual date:

$ dateround 2015-08-30 saturday
2015-09-05

If you need the input date to be in a specific format, like your 30-AUG-2015, you can use the -i or --input-format option, like:

$ dateround -i '%d-%b-%Y' 30-AUG-2015 saturday
2015-09-05
Related Question