title: Bash - success or failure - send email first and then exit
body: <p>I would like to run a bash script on the target server, whenever any command execution fails, I would like to first send email with error details and why it failed and then exit from the program</p>
  
  <p>I have tried redirecting the whole bash script execution to a log file and sending email the log file.</p>
  
  <p>Right now I am getting email with the file.log content only when the script is executed successfully, but I would like to receive email even when it failed also, with the details. Pleas help.</p>
  
  <pre><code>exec &gt; file.log 2&gt;&amp;1 
  
  case $(hostname) in
  abcd|defg)
  blah
  blah
  ;;
  
  ghij|klmn)
  blah
  eg: command failed here due to file not present
  blah
  ;;
  
  *) echo "Not found"
  esac
  echo -e "Sending $(cat file.log)" | mailx -s "Status" abcd@abcd.com
  </code></pre>