Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get and format yesterday's date on the command line?

I have a Perl script which will run in a cron job on linux suse. It will take as input a log file that was generated yesterday. The filename of the log contains the date (i.e. log.20100209)

Can I send yesterday's date with the format in the prompt? Should I create an additional script to get the date and execute? If so, how can I do that?

Thanks

perl myscript.pl -f log.20100209

Edit

Thanks for your help

It worked with:

perl myscript.pl -f log.`date --date='yesterday' '+%Y%m%d'`
like image 375
Cesar Avatar asked Feb 10 '10 19:02

Cesar


2 Answers

GNU date:

date --date='yesterday' '+%Y%m%d'
like image 185
Ignacio Vazquez-Abrams Avatar answered Oct 02 '22 12:10

Ignacio Vazquez-Abrams


You can get yesterday's date like this:

perl -we'@a=localtime(time-24*3600);printf "%04d%02d%02d", $a[5]+1900, $a[4]+1, $a[3]'

You can use this when calling your script at the prompt:

perl myscript.pl -f log.`perl -we'@a=localtime(time-24*3600);printf "%04d%02d%02d", $a[5]+1900, $a[4]+1, $a[3]'`

But this is unreadable, and I suggest you write a proper script that calculates yesterday's date, and then calls myscript.pl.

like image 24
Hans W Avatar answered Oct 02 '22 13:10

Hans W