Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do not interrupt script if command fails, but collect exit code

Tags:

linux

bash

I need to execute a command in a script with set -e set. This command is an exception to the general script flow, in that it could fail and that would not be critical: the script can continue. I want that command to not interrupt the script; instead I want to keep the exit code for later evaluation.

I have come up with the following script:

#!/bin/bash

set -e
false && res1=$? || res1=$?
true  && res2=$? || res2=$?
echo $res1
echo $res2

(My command would be in place of false or true)

Is this the right approach?

EDIT

Incidentally, this very similar construct does not work at all:

#!/bin/bash

set -e
false || res1=$? && res1=$?
true  || res2=$? && res2=$?
echo $res1
echo $res2

EDIT

Testing one of the suggestions:

#!/bin/bash

set -e
false || { res1=$?; true; }
true  || { res2=$?; true; }
echo $res1
echo $res2

This does not work. Result is:

1
(empty line)
like image 244
blueFast Avatar asked Jul 12 '26 22:07

blueFast


1 Answers

Don't try to use && and || to form a ternary expression; it's too fragile. Just use an if statement.

if cmd; then res=$?; else res=$?; fi

Better(?) yet, you can put the assignment in the condition itself, reducing repetition at the cost of having a seemingly vacuous if statement:

if cmd; res=$?; then :; fi

That might be more clearly written with a single || though:

{ cmd; res=$?; } || true

(Notice I've used true and : interchangeably; : is guaranteed by POSIX to be a shell built-in, but true is probably more readable.)

like image 188
chepner Avatar answered Jul 14 '26 14:07

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!