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?


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?

  • In order to use the percents in crontab, you have to escape them with the backslash "\%" – Alex Oct 3 '09 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? – swingfuture Oct 5 '09 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 '09 at 2:45
myscript.sh > output_$(date +%Y%m%d)
| improve this answer | |

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.

| improve this answer | |
./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).

| improve this answer | |
  • Markdown: you can do <code>`</code> – Paused until further notice. Oct 2 '09 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 '09 at 20:26

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

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.