Dnartreb925
Dnartreb925

Reputation: 17

Use of set -e in BASH

I wanted to know if it was possible to code that kind of line in a BASH program I would like to have something that looks like:

if set -e
    echo "Error"
fi

Actually my teacher just told that set -e stops the program when there is an error. I don't really know how it works. What I want is that when there is an error at any part of the program it does echo "Error"

I'm just learning how to use bash so my knowledge isn't very good yet.

Upvotes: 0

Views: 104

Answers (2)

John Kugelman
John Kugelman

Reputation: 362137

You can install a trap handler to execute custom code.

set -e
trap 'echo "Error $?"' ERR

...

# Simulate a command that fails by calling `exit` in a subshell.
(exit 3)

Upvotes: 0

arco444
arco444

Reputation: 22881

What I want is that when there is an error at any part of the program it does echo "Error"

You can use a trap:

trap "echo Error" ERR
cat ./file_that_doesnt_exist
echo "something after the error"

If you use this in combination with set -e the program will display the message and immediately exit - i.e. the echo won't run.

Upvotes: 2

Related Questions