Reputation: 3296
If in a script I use set -e
the script continues after an error has occurred in a statement that executes two commands with &&
.
For example:
set -e
cd nonexistingdirectory && echo "&&"
echo continue
This gives the following output:
./exit.sh: line 3: cd: nonexistingdirectory: No such file or directory
continue
I want the script to exit after cd nonexistingdirectory
and stop.
How can I do this?
** Edit**
I have multiple scripts using &&
that I need to fix to make sure they exit upon error. But I want a minimum impact/risk solution. I will try the solution mentioned in the comments to replace &&
with ;
combined with set -e
.
Upvotes: 2
Views: 2071
Reputation: 66
The problem here is your &&
command.
In fact, when a command that retrieves error is executed together (&&
) with another command, the set -e
doesn't work.
If you explain better the real use case we could find out a work around that fits your needs.
set [+abefhkmnptuvxBCEHPT] [+o option] [arg ...]
-e
Exit immediately if a pipeline (which may consist of a single simple command), a subshell command enclosed in parentheses, or one of the commands executed as part of a command list enclosed by braces (see SHELL GRAMMAR above) exits with a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test following the if or elif reserved words, part of any command executed in a && or || list except the command fol- lowing the final && or ||, any command in a pipeline but the last, or if the command's return value is being inverted with !.
from man bash
Upvotes: 5
Reputation: 85887
This is by design. If you use &&
, bash assumes you want to handle errors yourself, so it doesn't abort on failure in the first command.
Possible fix:
set -e
cd nonexistingdirectory
echo "&&"
echo continue
Now there are only two possibilities:
cd
succeeds and the script continues as usual.cd
fails and bash aborts execution because of set -e
.Upvotes: 4