Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid a bash script from failing when -e option is set?

I have a bash script with -e option set, which fails the whole script on the very first error.

In the script, I am trying to do an ls on a directory. But that path may or may not exist. If the path does not exist, the ls command fails, since the -e flag is set.

Is there a way by which I can prevent the script from failing?

As a side note, I have tried the trick to do an set +e and set -e before and after that command and it works. But I am looking for some better solution.

like image 619
Bhushan Avatar asked Sep 20 '12 01:09

Bhushan


People also ask

How do I stop a shell script from failing the command?

Exit When Any Command Fails This can actually be done with a single line using the set builtin command with the -e option. Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code.

What happens if you use set in a bash script?

In Bash, the set command allows you to manage certain flags and characteristics to influence how your bash scripts behave. These controls ensure that your scripts follow the correct path and that Bash's peculiar behavior does not cause difficulties.

What is set +E in bash?

Set –e is used within the Bash to stop execution instantly as a query exits while having a non-zero status. This function is also used when you need to know the error location in the running code.


1 Answers

You can "catch" the error using || and a command guaranteed to exit with 0 status:

ls $PATH || echo "$PATH does not exist" 

Since the compound command succeeds whether or not $PATH exists, set -e is not triggered and your script will not exit.

To suppress the error silently, you can use the true command:

ls $PATH || true 

To execute multiple commands, you can use one of the compound commands:

ls $PATH || { command1; command2; } 

or

ls $PATH || ( command1; command2 ) 

Just be sure nothing fails inside either compound command, either. One benefit of the second example is that you can turn off immediate-exit mode inside the subshell without affecting its status in the current shell:

ls $PATH || ( set +e; do-something-that-might-fail ) 
like image 99
chepner Avatar answered Sep 29 '22 02:09

chepner