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)
false ; res1=$?would be better? Would that record the result of the previous command, without interrupting script?