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.
You can “catch” the error using
||and a command guaranteed to exit with 0 status:Since the compound command succeeds whether or not
$PATHexists,set -eis not triggered and your script will not exit.To suppress the error silently, you can use the
truecommand:To execute multiple commands, you can use one of the compound commands:
or
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: