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
3
  • 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).
    – user313992
    Commented Dec 28, 2019 at 7:10
  • that did the trick, thanks :) Commented Dec 28, 2019 at 9: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). Commented Dec 28, 2019 at 22:13

1 Answer 1

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .