6

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
  • 2
    there was one or more Qs where this was debated at length, but of course there's a trivial solution for that: local why; why=$(false); echo $?; (btw, don't use uppercase names for local variables). –  Dec 28 '19 at 07:10
  • that did the trick, thanks :) – openCivilisation Dec 28 '19 at 09:39
  • BTW, arguably, one shouldn't use all-uppercase for any shell variables that aren't defined by the shell itself -- see the relevant POSIX spec, specifying that the shell and other POSIX-compliant tools may modify their behavior based only on all-caps environment variables, leaving variable names with at least one lowercase character safe for applications to use (relevant to shell variables that aren't explicitly exported since changing a shell variable overwrites any like-named environment variable). – Charles Duffy Dec 28 '19 at 22:13

1 Answers1

9

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.

schily
  • 19,173