I am using set -e
to abort on errors.
But for particular one function I want to ignore error and on error I want return code of the function.
Example:
do_work || true
if [ $? -ne 0 ]
then
echo "Error"
fi
But it is not work return code is always true due || true
How to get return code on do_work on error ?
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.
The -r tests if the file exists and if you have read permission on the file. Bash scripting tutorial - if statement. The meaning of -r depends on what program/command it is given as an argument for. In this case it is for [ , and means to check whether the file named by the next argument is readable.
To check the exit code we can simply print the $? special variable in bash. This variable will print the exit code of the last run command.
${} Parameter Substitution/Expansion A parameter, in Bash, is an entity that is used to store values. A parameter can be referenced by a number, a name, or by a special symbol. When a parameter is referenced by a number, it is called a positional parameter.
You could use a subshell shortcut:
( set +e; do_work )
if [ $? -ne 0 ]
then
echo "Error"
fi
Hope this helps =)
Several of the answers given here are not correct, because they result in a test against a variable that will be un-defined if do_work
succeeds.
We need to cover the successful case as well, so the answer is:
set -eu
do_work && status=0 || status=1
The poster's question is a little ambiguous because it says in the text "on error I want return code" but then the code implies "I always want the return code"
To illustrate, here is problematic code:
set -e
do_work() {
return 0
}
status=123
do_work || status=$?
echo $status
In this code the value printed is 123, and not 0 as we might hope for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With