How to run a bash script via Cron

I've had the same problem where log file was created empty and the only way to see what is going on was to add 2>&1 at the end of the cron job.

*/10 * * * * /home/users/me/backupS3.sh >> /home/users/me/backupS3.log 2>&1

If anybody wonders what 2>&1 actually mean here is a short explanation:

2 - refers to a file descriptor used to identify stderr

1 - refers to a file descriptor used to identify stdout

So 2>&1 basically translates to: Redirect stderrtostdout


In pathnames, the leading / doesn't mean "home directory"; it always refers to the root of the file system, no matter who you're logged in as. You need to use the actual full, absolute path to the script (e.g. /home/serverpilot/backupS3.sh). If the crontab belongs to the same user whose home directory holds the script, you can use "$HOME"/backupS3.sh and the system will fill in their home directory path for you. Or, even more simply, just use ./backupS3.sh, since cron jobs start with their working directory equal to their owner's home directory.

If that doesn't work, then either what you mean by "user directory" is not the same as the POSIX concept of "home directory", or the script is not executable (which you can fix by running the command chmod +x backupS3.sh once).

If you're not sure what the full path is, just run the pwd command while you're in the same directory that holds the script, and put the output, followed by a slash, in front of the script name.


First, change #!/bin/sh to #!/bin/bash, next use the full path to the script (also .sh isn't needed in the file name)

*/10 * * * * /home/users/me/backupS3.sh >> /home/users/me/backupS3.log  

Tags:

Bash

Cron