5

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.

1

2 Answers 2

4

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

#!/bin/bash

set -e

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

trap on_exit ERR

echo 'yes' | grep "$1"

In use:

$ ./script.sh yes
yes
$ ./script.sh no
This script has exited in error
4
  • As if there wasn't a recent flurry of questions about set -e being completely unreliable.
    – user313992
    Commented Jun 7, 2019 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
    Commented Jun 7, 2019 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.
    – user313992
    Commented Jun 7, 2019 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
    Commented Jun 7, 2019 at 20:23
0

If you want it to work on old sh too (instead just on bash):

#!/bin/sh
set -e
trap 'test $? -gt 0 && echo "This script has exited in error" >&2' 0

echo 'yes' | grep "$1"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .