Search code examples
bashcron

How to run a bash script via Cron


I have seen other questions that are similar but I can't find any real information on how to figure out the proper way to run a Bash script via Crontab. The .sh file is located in the user directory (in my case serverpilot).

The script is trying to copy the contents of the apps folder and send to my S3 bucket. The script works perfectly when run with sh backupS3.sh from the terminal but no joy via Cron. I've seen people reference PATH variables and the like but no idea where to even begin!

/backupS3.sh

#!/bin/sh
echo 'Started backing to S3'
date +'%a %b %e %H:%M:%S %Z %Y'
aws s3 sync /apps s3://bucketname
date +'%a %b %e %H:%M:%S %Z %Y'
echo 'Finished backing to S3'

crontab

*/10 * * * * /backupS3.sh >> backupS3.log  

Can anyone point me at anything obvious I'm doing wrong? Thanks!

EDIT: I've added 2>&1 on to the end of the cron command and now I am getting something in the log file:

/bin/sh: 1: /backupS3.sh: not found


Solution

  • 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.