mvdan / sh

A shell parser, formatter, and interpreter with bash support; includes shfmt
https://pkg.go.dev/mvdan.cc/sh/v3
BSD 3-Clause "New" or "Revised" License
7.27k stars 345 forks source link

interp: exit codes not working correctly with some substitutions #828

Closed andreynering closed 2 years ago

andreynering commented 2 years ago

Hey there,

Originally reported at https://github.com/go-task/task/discussions/687

Given this code:

test=$(exit 255)
echo $?

In Bash, it correctly returns the right exit code (255 in this case). But with this lib, it's always 0.

Is this a by design decision to not support this or a possible bug?

mvdan commented 2 years ago

I don't recall this being by design; we should follow Bash behavior in general. We might have a bug where assigning a variable forgets the inner exit code, for example. Happy to review a patch with a test :)

ghostsquad commented 2 years ago

@mvdan this happens even when not assigning it to a variable.

$(exit 2); echo $?
$(false); echo $?

both examples write 0

mvdan commented 2 years ago

The relevant part of the bash manual:

If there is a command name left after expansion, execution proceeds as described below. Otherwise, the command exits. If one of the expansions contained a command substitution, the exit status of the command is the exit status of the last command substitution performed. If there were no command substitutions, the command exits with a status of zero.

I wasn't aware of this. Not a good first issue after all, so I'm taking this one.