Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
810 views
in Technique[技术] by (71.8m points)

bash - Why does set -e; true && false && true not exit?

According to this accepted answer using the set -e builtin should suffice for a bash script to exit on the first error. Yet, the following script:

#!/usr/bin/env bash

set -e

echo "a"
echo "b"
echo "about to fail" && /bin/false && echo "foo"
echo "c"
echo "d"

prints:

$ ./foo.sh 
a
b
about to fail
c
d

removing the echo "foo" does stop the script; but why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To simplify EtanReisner's detailed answer, set -e only exits on an 'uncaught' error. In your case:

echo "about to fail" && /bin/false && echo "foo"

The failing code, /bin/false, is followed by && which tests its exit code. Since && tests the exit code, the assumption is that the programmer knew what he was doing and anticipated that this command might fail. Ergo, the script does not exit.

By contrast, consider:

echo "about to fail" && /bin/false

The program does not test or branch on the exit code of /bin/false. So, when /bin/false fails, set -e will cause the script to exit.

Alternative that exits when /bin/false fails

Consider:

set -e
echo "about to fail" && /bin/false ; echo "foo"

This version will exit if /bin/false fails. As in the case where && was used, the final statement echo "foo" would therefore only be executed if /bin/false were to succeed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...