Linux – bash script alert on error

bashlinuxscripting

I've a script which do. ls , cp, mv
I want if any of the command fail this should alert over email as well as after successful competition. Any idea? I can adjust email alert but want to know how to check for errors and successful attempt.

Best Answer

You can have a series of commands continue to execute until "failure" by using "&&" to run the commands in succession; each command returns "true", causing the following command to run. Then use "||" to run a command upon failure, such as:

#!/bin/bash

cp foo bar \
  && mv bar bar{,.bak} \
  && echo "good so far" \
  && ls file123 | tee -a /tmp/msg.txt \
  && mailx -u user -s "success" -f /tmp/msg.txt \
  ||  mailx -u user -s "failure" -f ~/err.txt

Since that can get messy, use functions, such as

#!/bin/bash

do_work() {
  mv... || return 1
  cp... || return 1
  return 0
}

report() {
  [ "$1" = "ok" ] && mailx ....
  [ "$1" != "ok" ] && mailx -s "$1" ....
  return 0
}

do_work \
  && report ok 
  || report err

Further, continuing from the above example, you can add blanket rules via a 'trap' in the script that will always execute certain commands if any type of error status is returned at any point in the script (including receiving a control-c (interrupt) signal while the script is running):

#!/bin/bash
tmp=/tmp/msg.$$.txt

# Cleanup: delete tmp files on exit. On any error, trap and exit... then cleanup
trap 'echo "cleaning up tmpfiles..." && rm $tmp >/dev/null 2>&1' 0
trap "exit 2" 1 2 3 15

...

do_work && exit 0

(Disclaimer... commands shown above are general pseudo-code, and just typed from memory without running them. Typos surely exist.)