I have created a bash script that runs automated EBS backups on AWS. It is kicked off via a cronjob:

0 2 * * * /bin/bash /root/backup_snapshots.sh > backup.log 2>&1

This works perfectly, but next thing I want to do is to add an exit code for whether or not the script runs successfully ( So I can configure a Nagios check on it). There is a few things I am going to be doing:

  1. Create the backup.log in /var/log/backup/ directory.
  2. Configure logrotate to rotate it daily, to make this check easier to detect.

But one question I have is, is it possible to have cron write an exit code to the backup.log file I created? Or should I go with this type of implementation:

Create crontab entry with a script that can kick off the actual script AND have an exit code like this:

/root/backup_snapshots.sh 2> /dev/null
if [ $? -eq 0 ]
  echo "PASS"
  echo "FAIL" >&2

I want to make this as simple as possible so if cron can do it, awesome! If not, would the next best thing would be to create a bash script that executes backup_snapshots.sh and run via cron?

  • I haven't used logger yet. Not sure how to really add logging to it via logger. But essentially, I need something in place that would add 3 codes.. One for pass, fail, and in_progress..
    – ryekayo
    Apr 24, 2017 at 20:36

1 Answer 1

exec 1>/var/log/backup/backup_sbapshots.log 2>&1
if /root/backup_snapshots.sh
  echo "PASS"
  echo "FAIL"

Make your cron script as shown which will put the cronjob run status in the backup log file. Note that there's no mention anywhere of the $? variable as the if statement does it own it's own.

  • Thanks for this information. One question: when you use the exec command, should that be pointed to the actual script that runs the backups or the log file that is created?
    – ryekayo
    Apr 24, 2017 at 20:28
  • exec .. should be pointed to the logs or wherever you want the dumps from your script to be stored in. We exec once at the top to avoid having to do a redirection everytime the script outputs/errors something, as that sets the stage for all times to come during the script's run.
    – user218374
    Apr 24, 2017 at 20:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .