Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't sh with errexit work with a command list?

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.

like image 544
August Karlstrom Avatar asked May 16 '19 19:05

August Karlstrom


People also ask

How to check the exit status of a command in Linux?

“$?” 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.

How to echo exit code of command?

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.

What does exit status 2 mean?

Exit code 2 signifies invalid usage of some shell built-in command. Examples of built-in commands include alias, echo, and printf.

How do I stop a shell script from error?

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.


1 Answers

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.

like image 93
3 revs, 2 users 88% Avatar answered Oct 13 '22 20:10

3 revs, 2 users 88%