Why does "local" sweep the return code of a command?

BashShellLocal

Bash Problem Overview


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?

Bash Solutions


Solution 1 - Bash

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

Solution 2 - Bash

The return code of the local command obscures the return code of false

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontoklandView Question on Stackoverflow
Solution 1 - BashSiegeXView Answer on Stackoverflow
Solution 2 - BashIgnacio Vazquez-AbramsView Answer on Stackoverflow