cron a script and output to file named with date stamp

I can do this from the command line:

/home/mylogin/tests/script.sh > /home/mylogin/tests/`date +"%Y%m%d"`log.csv

It yields a file named: 20110429log.csv

I would like to schedule with cron to run daily.

when I enter the same line, as above in cron:

10 16 * * * /home/mylogin/tests/script.sh > /home/mylogin/tests/`date +"%Y%m%d"`log.csv

...it trucates at the first percent sign and yields a cron error:
unexpected EOF while looking for matching ``'
...cron executes:
/home/mylogin/tests/script.sh > /home/mylogin/tests/`date +"

It was suggested that I escape the percent sign:

10 16 * * * /home/mylogin/tests/script.sh > /home/mylogin/tests/`date +"\%Y\%m\%d"`log.csv

However, that doesn't seem to execute at all. I get no ouitput file and no sign of a cron error.

Any insight would be greatly appreciated.

Thanks,
-dog

Backticks mean you want your shell execute the command, but clearly shell is not there to do this when crontab job is executed. I would leave detailed explanation to someone more competent; but I can offer a workaround: Stick the redirection into your script:

 $ cat /home/mylogin/tests/script.sh
#!/bin/bash
(
 #whatever your script is doing
) > /home/mylogin/tests/`date +%Y%m%d`log.csv 

This will run the body of the script in subshell and capture the output into the file

1 Like

When I use cron I've found that it is almost always necessary to fully qualify executables. So you might try putting the path in front of the date command.

Also, you might try using single quotes in conjunction with your backticks.

Something along these lines:

/home/mylogin/tests/script.sh > /home/mylogin/tests/`/bin/date +'%Y%m%d'`log.csv

You may find that just pathing the date command does it for you. (I'm not on my unix box right now and don't recall off the top of my head if date is in /bin)

Good luck!

1 Like

I was unable to get the complete output of the script using redirection. I only got the first line.

I was able to get the original cron command line working. I had copied my script to another directory and had neglected to set execute permissions.

Thanks for your help and suggestions!
-dog