How to redirect output to a file from within cron?

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.


disclaimer [1].

I would like to add a footnote or addendum to @RanRag's answer.

Make sure your shell redirection syntax conforms to /bin/sh. If you try to use shell redirection syntax that is not valid with /bin/sh then your command will fail and your cron job will not ever run.

In your /etc/cron.d/example1 config files if you specify a user other than root and that user's login shell is not /bin/bash... you must still use /bin/sh syntax in /etc/cron.d/example1 command.


For example

If your user has shell csh or zsh or ksh set for his login shell. In your /etc/cron.d/example1 config file, the command must use /bin/sh syntax. Specifically any shell redirection must be /bin/sh syntax.

If you try to use for example csh shell redirect syntax in your /etc/cron.d/example1, then your cron job will never run. The logfile for crond located at /var/log/cron shall say that the command is run but the command will error out with a syntax error before your command gets run.

Where does crond emit error messages for a syntax error?

The error is not ever reported in /var/log/cron. crond instead by default emits any error messages using mail. So you must check /var/spool/mail/${USER} to see what is the error.

[1]

Disclaimer

  • This answer assumes a sysv system
  • systemd information may differ
  • Specifically this information was learned for centos-6 distro and may not apply to different sysv distros
    • I mention centos-6 specifically, because different distros may have a different crond implementation that differs from centos-6