Linux School -- Easy Shell Script Date Manipulation
Bill Malchisky June 10 2013 01:00:00 AM
In writing a few script files recently, I became reminded that if I run the shell script past midnight, but seek to use yesterday's date in the filename for accuracy, I would have to add several lines of creative code to complete this, while taking into account DST and in one case, a timezone delta between me and the server. I then stumbled upon 'yest'.Yest is an open source project specifically designed to allow for easy date manipulation. By default, it provides yesterday's date, otherwise, it takes today's date then adds or subtracts values from the arguments and outputs the result in one line of code. Very handy in shell scripts. The bonus is that it accepts all of date's formatting parameters. Thus, very little need change in your existing scripts. It is also a gem for dynamic log file naming, and accounts for DST automatically.
Ensure you peruse the readme file as you will need to compile the code, but that is also just one statement. Copy the man page to the proper directly (also in the readme file) and you are all set.
Terminal Examples
$ date
Sat Jun 8 01:36:48 EDT 2013
$ yest
06/07/2013
$ yest -15
05/24/2013
$ yest +30
07/08/2013
$ yest +30 +%Y-%m-%d
2013-07-08
Script Example
#!/bin/bash
_date=$(yest +30 "+%Y-%m-%d")
echo $_date
Script Execution
$ chmod 750 test.sh
$ ./test.sh
2013-07-08
- Comments [0]