When invoked without arguments, the date command displays the current date and time. Depending on the options specified, the date would set the date and time or print it in a user-defined format. However, how do you get yesterdays with bash shell script? What about tomorrows day? I have seen many sysadmins writing Perl scripts for calculating relative dates such as yesterdays or tomorrows day. You can use the GNU date command or BSD/date command, which is designed to handle relative date calculation such as:
Let us see how to get yesterday’s date in bash on Linux operating systems.
The syntax and sample examples are as follows:
The syntax is as follows:
date --date="STRING"
date --date="next Friday"
date --date="2 days ago"
date --date="yesterday"
date --date="yesterday" +"%format"
## Get yesterday's date in dd-mm-yy format
date --date="yesterday" +"%d-%m-%y"
date --date="yesterday" +"%m-%d-%y" ## US date format
date --date="yesterday" +"%Y-%m-%d" ## YYYY-mm-dd format
### store y'day date in a shell variable called yday and display it ##
yday=$(date --date="yesterday" +"%Y-%m-%d")
echo "$yday"
The --date=STRING is a human-readable format such as “next Thursday” or “1 month ago”. A date string may contain items indicating calendar date, time of day, time zone, day of the week, relative time, relative date, and numbers. See “How To Format Date For Display or Use In a Shell Script” for more about +“%format” stings.
First, try to display today’s date, enter:
$ date
Sample outputs:
Wed Jun 15 04:47:45 IST 2011
To display yesterday’s date, enter:
$ date --date="1 days ago"
$ date --date="1 day ago"
$ date --date="yesterday"
$ date --date="-1 day"
Sample outputs:
Tue Jun 14 04:54:40 IST 2011
You can use various string formats to produce the same output. Please note that the output of the date command is not always acceptable as a date string, not only because of the language problem but also because there is no standard meaning for time zone items like IST or EST.
Type the following command
$ date --date="-1 days ago"
Or
$ date --date="next day"
#linux