I am using following options
set -o pipefail
set -e
In bash script to stop execution on error. I have 100 of script executing and I don't want to check return code of the script.
But for a particular script I want to ignore the error. How can I do that ?
The solution:
particular_script || true
Example:
$ cat /tmp/1.sh
particular_script()
{
false
}
set -e
echo ein
particular_script || true
echo zwei
particular_script
echo drei
$ bash /tmp/1.sh
ein
zwei
drei
will be never printed.
Also, I want to add that when pipefail
is on,
it is enough for shell to think that the entire pipe has non-zero exit code
when one of commands in the pipe has non-zero exit code (with pipefail
off it must the last one).
$ set -o pipefail
$ false | true ; echo $?
1
$ set +o pipefail
$ false | true ; echo $?
0
Just add || true
after the command where you want to ignore the error.
More concisely:
! particular_script
From the POSIX specification regarding set -e
(emphasis mine):
When this option is on, if a simple command fails for any of the reasons listed in Consequences of Shell Errors or returns an exit status value >0, and is not part of the compound list following a while, until, or if keyword, and is not a part of an AND or OR list, and is not a pipeline preceded by the ! reserved word, then the shell shall immediately exit.
Just in case if you want your script not to stop if a particular command fails and you also want to save error code of failed command:
code
set -e;
command || EXIT_CODE=$? && true ;
echo $EXIT_CODE
Instead of "returning true", you can also use the "noop" or null utility (as referred in the POSIX specs) :
and just "do nothing". You'll save a few letters. :)
#!/usr/bin/env bash
set -e
man nonexistentghing || :
echo "It's ok.."
I have been using the snippet below when working with CLI tools and I want to know if some resource exist or not, but I don't care about the output.
if [ -z "$(cat no_exist 2>&1 >/dev/null)" ]; then
echo "none exist actually exist!"
fi