Why does “local” sweep the return code of a comman

2019-01-01 13:36发布

This Bash snippet works as I would've expected:

$ fun1() { x=$(false); echo "exit code: $?"; }
$ fun1
exit code: 1

But this one, using local, does not:

$ 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 shell local
2条回答
梦醉为红颜
2楼-- · 2019-01-01 14:18

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
查看更多
栀子花@的思念
3楼-- · 2019-01-01 14:20

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

查看更多
登录 后发表回答