I have a /bin/foo shell script file.

How to exit a shell script on error AND message the user?

If I simply use a set -e then it exits on error, but no commands running when it hits error, like sending a message to STDOUT or sending a mail.

The question: how to run a command if the shell script runs to an error?

SLES12, bash.


You can create a function to message your user and use trap to have it execute when the script exits in error:


set -e

on_exit () {
    echo "This script has exited in error"

trap on_exit ERR

echo 'yes' | grep "$1"

In use:

$ ./script.sh yes
$ ./script.sh no
This script has exited in error
  • As if there wasn't a recent flurry of questions about set -e being completely unreliable. – Uncle Billy Jun 7 '19 at 20:02
  • @UncleBilly: I don't know what you're talking about but this Q/A has nothing to do with the reliability of set -e. That is working exactly how it should. – jesse_b Jun 7 '19 at 20:04
  • Is it? What if the error happens inside a func? Would your trap be called or not? Also, think through whether/why do you need set -e at all. – Uncle Billy Jun 7 '19 at 20:21
  • It absolutely is. It would work fine with a function as long as the function was built properly. set -e is not really needed though when trapping err. – jesse_b Jun 7 '19 at 20:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.