3

I wrote some bash script that does some backup job. I run the script with errexit and pipefail so I won't miss any error. The thing I want now is the script sending me an email in case an error occures. I got this working. But I want the scripts errors to be included in the email body. How can I do this?

here is the script:

#!/bin/bash
# exit script if an error occures
set -o errexit
# even exit if an error in passed through a pipe
set -o pipefail

trap 'ERRORMESSAGE_HERE | mailx -s "Something went wrong on srv-002" mymail@mycompany.ch' ERR

# the backup job here

# if script reaches this point everything went perfectly good
echo "all good!"

Thanks a lot for your help!

Jolta
  • 2,620
  • 1
  • 29
  • 42
Mike Dynamite
  • 65
  • 2
  • 8
  • http://stackoverflow.com/questions/6784295/capturing-and-mailing-bash-script-errors - this seems to be a relevant question, take a look at the answer if it suits you. – Yuriy Nov 14 '12 at 09:40

1 Answers1

3

how about(untested):

{
    # do the work here
} 2> >(mailx -s "job errors" recipient@example.com)
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • This should work. Alternatively just append `2> >(mailx -s "job errors" recipient@example.com)` when you run your script (if you schedule it with `cron`) or write a simple wrapper that does this (if you run it manually). – Anders Johansson Dec 01 '12 at 16:06
  • I confirm, it works very well! My test: `ls notExistingDir 2> >(mailx -s "job errors" recipient@example.com)` – Genjo Jan 19 '18 at 09:20