I just started learning bash and I was reading about the $? variable. From what I understood, $? is assigned to the exit status of the last command executed.
For example
$ false; echo $?
Will yield 1, and
$ false; :; echo $?
Will yield 0
Things get a bit more complicated when I combine these with if/for blocks. The man page reads:
forNAME [inWORDS ... ];doCOMMANDS;doneExecute commands for each member in a list.
The
forloop executes a sequence of commands for each member in a list of items. Ifin WORDS ...;is not present, thenin "$@"is assumed. For each element in WORDS, NAME is set to that element, and the COMMANDS are executed.Exit Status:
Returns the status of the last command executed.
That means:
$ false; for i in 1 2 3; do false; done; echo $?
Will yield 1 since the last command executed is false. But
$ false; for i in; do false; done; echo $?
or
$ false; if false; then :; fi; echo $?
Will yield 0 despite the fact that false was the last command executed.
My guess is the $? variable is set to 0 when entering a for/if block. Am I missing something?
According to bash's manual:
iflist ;thenlist ; [eliflist ;thenlist ; ] ... [elselist ; ]fiThe
iflistis executed. If its exit status is zero, thethenlistis executed. Otherwise, eacheliflistis executed in turn, and if its exit status is zero, the correspondingthenlistis executed and the command completes. Otherwise, theelselistis executed, if present. The exit status (of the wholeif ... fiblock) is the exit status of the last command (in thethen,eliforelseblock) executed, or zero if no condition tested true.
yes, after if ..;, for ..; or while ..; statements the exit status reset to 0.
to be clear this doesn't mean after fi; or done; because the exit status is the last command exit status.
EDIT : commands between if/elif and then doesn't affect exit status of compound statement whereas latest command executed between then/else and elif/fi sets the exit status of compound statement.
after a function call; the exit status will be the value returned by return or the exit status of last command.
with the option set -e, set -o errexit; the shell exits after a command with a <>0 exit status, except if followed by || or inside a if ..; statement.
exit status must be checked just after command exits, logical operators can be used &&, ||:
# to fail fast the process can't continue
simple_command || {
echo "failed .."
exit 1
}
the error handling is similar to exceptions, the question to be asked is does or how the process can continue after a command fails?
in pipeline commands the exit status is the exit status of the last command except with set -o pipefail : the exit status will be the exit status of the latest command in the pipe with exit status <>0.
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