Backup script not working in cron

Q I have been writing a small script that makes a backup of some files from one server to another over FTP. The script works fine when executed at the command line over SSH. However, when scheduled to run every two hours something is not working and the script gets run repeatedly.

* */2 * * * /bin/bash /home/aport/ >/dev/null 2>&1

To work around the problem I modified the script to repeat itself every two hours in an infinite loop. This worked when signed in interactively over SSH. Yet disaster struck again when I started the script in the background as /bin/bash ./ >/dev/null 2>&1 & All works well until I try to exit the SSH session where my SSH client, Putty, inexplicably hangs and has to be closed manually. If I log in again I see that the script is still running through ps. Help!

A Since the minute field in the above crontab has not been populated, the scheduled job above finds itself running the script every minute for every second hour. The amended crontab should run the script at five minutes past every two hours:

5 */2 * * * /bin/bash /home/aport/ >/dev/null 2>&1

The second issue seems to relate to the fact that when the script was executed in the background it was not fully detached from the controlling terminal. The following recipe will allow you to background the script and exit the SSH session.

$ nohup /bin/bash  >/dev/null 2>&1 >/dev/null &

Besides having both standard output and standard error redirected to /dev/null, standard input is redirected from /dev/null while nohup makes the executed command immune to any hangup signals. If output is not redirected, nohup will write any output to the file nohup.out, which may be desirable to audit the outcome of your backup script.

Follow us on or Twitter

Username:   Password:
Create Account | About TuxRadar