Bash Retrieve Exit Code of Subshell Using Local – How to

exitexit-statussubshell

This question is close to others – Can I get the exit code from a sub shell launched with $(command)?

However there are no solutions I've found that allows me to get an exit code from a sub shell when using local and eval as in this example…

test() {
> local WHY="$(eval "echo 'test'"; exit 3)"; echo $?
> }
test
0

Best Answer

This is simple: Do not use a single command but split:

test() {
    local why
    why="$(eval "echo 'test'"; exit 3)"; echo $?
}
test
3

The problem was that local is a builtin command with an own exit code...If you avoid that command at the same time as the variable assignment, you get the exit code from the subshell.