4

I'm trying to get Previous date of reference file.

What I've tried :

[rahul@testsrv]$ date +%F -r /tmp/ftpbkp.log
2013-08-27

[rahul@testsrv]$ date +%F -r /tmp/ftpbkp.log -d "1 day ago"
date: the options to specify dates for printing are mutually exclusive
Try `date --help' for more information.
slm
  • 369,824
Rahul Patil
  • 24,711

4 Answers4

5

A note of warning:

$ date -r ~/a
Sun 28 Oct 23:12:00 GMT 2012
$ LC_ALL=C date -r ~/a
Sun Oct 28 23:12:00 GMT 2012

As output, date outputs the date in the user's local format. As input to -d GNU date is more picky on the format though:

$ date -d "$(date -r ~/a) - 1 day"
date: invalid date ‘Sun 28 Oct 23:12:00 GMT 2012 - 1 day’

Fixing locale to C fixes that issue:

$ export LC_ALL=C
$ date -d "$(date -r ~/a) - 1 day"
Sun Oct 28 00:12:00 BST 2012

But note how the date is still 2012-10-28, though now in summer time. That's because 24 hours before that date in Britain, we were still the same day.

Now, if you want the day before, you'd have to write it:

date -d "$(date -r /tmp/file.ref +'%F -1 day')" +%F
4
LC_ALL=C date -d "$(LC_ALL=C date -r /tmp/ftpbkp.log) - 1 day" +%F

If GNU date is not available:

perl -MPOSIX -le'
  print strftime("%Y-%m-%d", localtime +(stat shift)[9] - 24*60*60)
  ' /tmp/ftpbkp.log
2
date -r /tmp/ftpbkp.log +%s | awk '{print strftime("%F", $1 - (24*60*60) );}'
slm
  • 369,824
ash
  • 7,260
1

The -d option is used for specifying a different time than the current time. You asked date command to format the last modification time of file /tmp/ftpbkp.log according the format %F and additionally you passed it another time specified by -d option. These option are mutually exclusive. But there is a trick how to combine it:

date -d "`date -r /tmp/ftpbkp.log`" - 1 day"
dsmsk80
  • 3,068
  • 1
    The backticks are deprecated, use $() instead. Also what else does this add beyond what Dimitre's answer provided? – slm Aug 28 '13 at 13:24
  • I wrote it at the same time so basically nothing :-) – dsmsk80 Aug 28 '13 at 13:28
  • @slm, good comment up there. You should use $() command substitution all the time since it offers more flexibility in nesting commands and avoiding entering sometimes unnecessary " " double quotes or ' ' single quotes – Valentin Bajrami Aug 28 '13 at 13:45
  • @val0x00ff, would you care to expand how $() avoids entering quotes? – Stéphane Chazelas Aug 28 '13 at 14:33
  • @StephaneChazelas I am not saying it avoids entering quotes. What I am saying is: When using backticks ```` You need to use more quotes to escape other quotes which will make a line of code illegible. So nested quoting inside $() is far more convenient. Compare these two

    x=$(grep "$(dirname "$somepathpath")" file) x=grep "\dirname "$somepath"`" file

    http://mywiki.wooledge.org/BashFAQ/082

    – Valentin Bajrami Aug 28 '13 at 14:41