This Bash snippet works as expected:
$ fun1() { x=$(false); echo "exit code: $?"; } $ fun1 exit code: 1
But this one, using local
, does not as I would have expected:
$ fun2() { local x=$(false); echo "exit code: $?"; } $ fun2 exit code: 0
Can anyone explain why does local
sweep the return code of the command?
Extracting the elusive exit code To display the exit code for the last command you ran on the command line, use the following command: $ echo $?
How to get the exit code of a command. To get the exit code of a command type echo $? at the command prompt. In the following example a file is printed to the terminal using the cat command.
Overview. In Linux, when a process is terminated, it returns an exit code. Upon successful execution, this code is equal to zero. Any non-zero exit code indicates that some error occurred.
false returns an exit status value of 1 (failure). It ignores any arguments given on the command line. This option can be useful in shell scripts.
The reason the code with local
returns 0 is because $?
"Expands to the exit status of the most recently executed foreground pipeline." Thus $?
is returning the success of local
You can fix this behavior by separating the declaration of x
from the initialization of x
like so:
$ fun() { local x; x=$(false); echo "exit code: $?"; }; fun exit code: 1
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