#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2010
    Posts
    21
    Rep Power
    0

    Email Error Notifications on Cron Bash Script mv cp rsync


    Wondering if anyone can point me to an example of how to setup a bash script that executes cp mv and rsync commands and only sends an email if there were errors with any of those commands and what the errors are. In addition it should email if the cron event to execute the script fails, or in other words if the bash script doesn't run at all or exits prematurely with an error.

    Thank you!
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2006
    Posts
    2,616
    Rep Power
    1766
    Check the value of $? (store it in a variable for later reference) after each 'critical' command:
    Code:
    num_errors=0
    mv this to.that
    mv_cc=$?
    if [ $mv_cc != 0 ]
    then
      num_errors+=1
      echo do something here
    fi
    cp over.there to.here
    cp_cc=$?
    if [$cp_cc != 0]
    then
      num_errors+=1
      do something about copy fail
    fi
    command -x -y -x >$$.out.txt 2>$$.err.txt
    cmd_cc=$?
    if [ $cmd_cc != 0]
    then
      num_errors+=1
      parse $$.out.txt to determine more info about fail
    fi 
    .
    .
    . more stuff ...
    .
    if [ $num_errors > 0 ]
    then
      echo Arrange a mail saying all that has gone wrong
    fi
    Not sure about Linux but most Unix systems drop the owning user a mail in the event of a cron job failing, so no need to do much there
    The moon on the one hand, the dawn on the other:
    The moon is my sister, the dawn is my brother.
    The moon on my left and the dawn on my right.
    My brother, good morning: my sister, good night.
    -- Hilaire Belloc
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2015
    Posts
    54
    Rep Power
    3
    Yes, cron will email the owner of the account under which the crontab is running.

    You may also use the MAILTO environment variable to send any output generated by your script to a specific email address, e.g.:

    MAILTO=your_email@domain.com
    0 10 * * * /path/to/bash_script

IMN logo majestic logo threadwatch logo seochat tools logo