Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash ignore error and get return code

Tags:

bash

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 ?

like image 760
Vivek Goel Avatar asked Oct 22 '12 11:10

Vivek Goel


People also ask

What does [- Z $1 mean in bash?

$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.

What does \r do in bash?

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.

How do I find my bash return code?

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.

What does ${} mean in bash?

${} 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.


2 Answers

You could use a subshell shortcut:

( set +e; do_work )
 if [ $? -ne 0 ]
  then
   echo "Error"
  fi

Hope this helps =)

like image 186
Janito Vaqueiro Ferreira Filho Avatar answered Oct 01 '22 14:10

Janito Vaqueiro Ferreira Filho


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.

like image 23
Mark Avatar answered Oct 01 '22 15:10

Mark