5

I need create log files that are essentially date stamps with prefix yp_ and suffix .log, and a manipulated day number:

$ touch yp_$(echo "$(date +%Y%m%d)-10" | /usr/bin/bc -l).log
$ ls
yp_20150912.log   # ... ok for today's date.

That's fine for today, but all hell breaks loose when the day's number is between 01 and 10 included. The result cannot be interpreted as a date stamp any longer.

E.g. just imagine that the day is the 8th of March, 2016, i.e. '20160308'. How do I code the above to make sure that subtracting 10 days will produce not '20150298' but '20150227' ? Also test yr answer with 19820103 ...

-- I looked at man date.

-- apropos date spews out 161 hits that I also reviewed.

Can somebody help with that one-liner?

3
  • GNU date, out of interest?
    – bertieb
    Sep 22, 2015 at 16:20
  • @bertieb: Yup, GNU date it is. My first example IS a leap-year !
    – Cbhihe
    Sep 22, 2015 at 16:22
  • Welp, GNU date to the rescue then :)
    – bertieb
    Sep 22, 2015 at 16:27

2 Answers 2

6

I need to manipulate dates (whilst paying attention to leap years)

Fortunately, GNU date has a very handy -d option:

-d, --date=STRING
          display time described by STRING, not 'now'

(from man date)

This accepts arbitrary date descriptions, like "now + 1 year" "Jan 28 + 3 weeks"; or in your case: "now - 10 days":

touch yp_$(date -d 'now - 10 days' +%Y%m%d).log

No need for messy invocations of bc, no worrying about leap years- GNU date will handle it.

2
  • 1
    Right on. This is exactly what I had in mind AND I had seen that option on the man page, but had not understood its use. Thanks - PS: BTW the "land of rain and drink" could be a lot of places... any place north of me, actually. :))
    – Cbhihe
    Sep 22, 2015 at 20:07
  • @Cbhihe Glad it worked for you- it's an incredibly useful thing to know about (and a feature I miss when not available in other languages) :) PS about 55° N, and rain on more days than not- make of what what you will ;)
    – bertieb
    Sep 22, 2015 at 20:13
6

To display a formatted date for x-days from today:

$ echo $(date +%Y%m%d)
20150922

$ echo $(date -d -10days +%Y%m%d)
20150912

$ echo $(date -d +10days +%Y%m%d)
20151002
1
  • 2
    I liked the concision of your answer and the answer is dead right. But it just came after @bertieb 's own, which is equally right. So I can only upvote you. Tx Steven and sorry for that.
    – Cbhihe
    Sep 22, 2015 at 20:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .