1

I have some shell script which generates some outputs. The output is written into a file. In my cronjob I have it: ./myscript.sh --options > output Because the cronjob runs every week, I would like to keep a list of outputs instead of overwritting them every time the script runs. So ideally I would like to have the output file name as output_date. Date is current script running date. In Unix, date command can give you current date info, but how could I integrate that into the output file name?

Update:

Have tried Heath and wfaulk's methods, it does work well. However, when I put the same command in cronjob, I started to get the error: /bin/sh: -c: line 0: unexpected EOF while looking for matching `)' /bin/sh: -c: line 1: syntax error: unexpected end of file

I know it's caused by output to a file named output_$(date +%Y%m%d) since that's the only change I made. Is there a different way to do it in cronjob?

3
  • In order to use the percents in crontab, you have to escape them with the backslash "\%"
    – Alex
    Oct 3, 2009 at 1:20
  • Yeah, that worked (made a mistake earlier on while using backslash). One more thing, how do I output not only current date, but also for example a week ago? So today is Oct 5, I would like the output file being like: output_20090928_20091005. $(date +%Y%m%d) generates 20091005, how to get 20090928? Oct 5, 2009 at 19:34
  • With gnu date, You can have date to "calendar math" by adding the --date parameter but instead of a numeric date you can use relative dates like: date +Y%m%d --date "-1 week"
    – Alex
    Oct 8, 2009 at 2:45

4 Answers 4

5
myscript.sh > output_$(date +%Y%m%d)
0
3

The date command does what you asked for, but logrotate is meant for what you are trying to do and will keep things cleaned up... It is worth learning in my opinion.

2
./myscript.sh --options > output_$(date)

But you probably want to use a different date format so that it doesn't have spaces and junk in it. Something like:

./myscript.sh --options > output_$(date +%Y%m%d.%H%M%S)

On the off chance that your shell doesn't support the $() syntax, replace the $( and its matching ) each with a "`" (backtick).

2
  • Markdown: you can do <code>`</code> Oct 2, 2009 at 19:45
  • Why did I think that was a block and not an inline element to the point of not even trying?
    – wfaulk
    Oct 2, 2009 at 20:26
0

./myscript.sh --options > output_$(date)

You must log in to answer this question.

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