26

How can I check the exit code of a command substitution in bash if the assignment is to a local variable in a function?
Please see the following examples. The second one is where I want to check the exit code.
Does someone have a good work-around or correct solution for this?

$ function testing { test="$(return 1)"; echo $?; }; testing
1
$ function testing { local test="$(return 1)"; echo $?; }; testing
0
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Vampire
  • 35,631
  • 4
  • 76
  • 102

1 Answers1

31

If you look at the man file for local (which is actually just the BASH builtins man page), it is treated as its own command, which gives an exit code of 0 upon successfully creating the local variable. So local is overwriting the last-executed error code.

Try this:

function testing { local test; test="$(return 1)"; echo $?; }; testing

EDIT: I went ahead and tried it for you, and it works.

Chriszuma
  • 4,464
  • 22
  • 19
  • 1
    Thanks, like always, right after I posted my question I found the answer myself which comes out as the same you suggest. I just have too less of a reputation to answer my own questions before 8 hours have passed. But `man local` gives me the man page of `LOCAL(8postfix)` manpage, so not too useful. But I found it on http://mywiki.wooledge.org/BashPitfalls#local_varname.3D.24.28command.29 – Vampire Mar 02 '12 at 06:09
  • Another source of information would be `man bash`. `local` is mentioned under the "SHELL BUILTIN COMMANDS" section. – Victor Zamanian Feb 18 '13 at 18:12
  • The `help` command returns documentation on built-in commands. See `help local`. – Eliot Aug 02 '17 at 20:41