Bash Cron – How to Redirect Output to a File from Within Cron

bashcronio-redirection

I have a backup script which I need to run at a particular time of a day so I am using cron for this task and from within cron am also trying to redirect the output of backup script to a logfile.

crontab -e

*/1 * * * * /home/ranveer/backup.sh &>> /home/ranveer/backup.log

In the above cron entry I am redirecting both stderr and stdout to a log file.

The above cron job executes fine according to syslog and it performs the task mentioned in the backup.sh file but it doesn't write anything to the log file.

/var/log/syslog

Oct 19 20:26:01 ranveer CRON[15214]: (ranveer) CMD (/home/ranveer/backup.sh &>> /home/ranveer/backup.log)

When I run the script from cli it works as required and output is written to a log file

ranveer@ranveer:~$ ./backup.sh &>> backup.log 
ranveer@ranveer:~$ cat backup.log
Fri Oct 19 20:28:01 IST 2012
successfully copied testdir
test.txt successfully copied
-------------------------------------------------------------------------------------
ranveer@ranveer:~$ 

So, why the output of file is not getting redirected to the file from within cron.

Best Answer

I solved the problem. There are two ways:

M1

Change the redirection from &>> to 2>&1. So now crontab -e looks like

*/1 * * * * /home/ranveer/vimbackup.sh >> /home/ranveer/vimbackup.log 2>&1

I believe the above works because by default cron is using sh to run the task instead of bash so &>> is not supported by sh.

M2

Change the default shell by adding SHELL=/bin/bash in the crontab -e file.

Related Question