Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore return value different then 0 when I have set -e?

Tags:

bash

I often add set -e in my bash scripts. However this time I have to call a command that returns some meaningless number instead of 0 on success. How can I tell bash to ignore the return value of this command only.

Changing the command, or changing it's code to conform to the standard is not an option.

like image 478
Dimitar Slavchev Avatar asked Nov 28 '12 16:11

Dimitar Slavchev


2 Answers

true always returns a zero exit code. So you can do

command-with-meaningless-return-value || true
like image 78
nandhp Avatar answered Oct 06 '22 04:10

nandhp


If you need to use the value of $? later, you can do:

# A test funtion to demonstrate different exit status values
$ exit_with(){ return $1; }

$ exit_with 0

$ echo $?
0

$ exit_with 4

$ echo $?
4

$ exit_with 4 || true

$ echo $?
0

# capture the exit status rather than clobber it
$ exit_with 4 || exit_status=$?

$ echo $?
0

$ echo $exit_status
4

In this case use $exit_status instead of $?. I've not found a way to do something like ?=$? or declare ?=$?

like image 35
Bruno Bronosky Avatar answered Oct 06 '22 03:10

Bruno Bronosky