If I run the following shell script as a normal user, it aborts at line three as expected:
set -o errexit
echo foo > /bar
echo $?
Here is the output:
$ sh test1.sh
test.sh: 3: test.sh: cannot create /bar: Permission denied
However, if the echo command is a part of a compound list, the execution continues after the failing command and prints the exit code:
set -o errexit
{ echo foo; } > /bar
echo $?
Here is the output:
$ sh test2.sh
test.sh: 3: test.sh: cannot create /bar: Permission denied
2
How come the script doesn't abort? On the other hand, if I change the curly braces to parentheses it works like how I would expect.
“$?” is a variable that holds the return value of the last executed command. “echo $?” displays 0 if the last command has been successfully executed and displays a non-zero value if some error has occurred. The bash sets “$?” To the exit status of the last executed process.
Extracting the elusive exit code To display the exit code for the last command you ran on the command line, use the following command: $ echo $? The displayed response contains no pomp or circumstance. It's simply a number.
Exit code 2 signifies invalid usage of some shell built-in command. Examples of built-in commands include alias, echo, and printf.
To end a shell script and set its exit status, use the exit command. Give exit the exit status that your script should have. If it has no explicit status, it will exit with the status of the last command run.
The POSIX specification states that a shell "may exit" if a redirection error occurs with a compound command.
bash
chooses to exit if the compound command is a subshell command ((...)
), but otherwise chooses not to. I am not aware of the rationale for this distinction; it may be historical in nature.
set -e
has many quirks, and often will not behave the way you expect. Many people advise that you simply not use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With