Why does local out=$(cmd) hide the command's exit status?

November 19, 2026 4 answers
Asked by c.752+plendrix

In a Bash function, I noticed that local out=$(false) reports success, but declaring out first and then assigning out=$(false) reports failure. Why are they different, and what's a good way to handle this?

Answers

5u~marblegasket_683

In local out=$(false), the status you see is from local, which normally succeeds in declaring the variable. The command substitution ran, but its failure isn't the status of that statement.

Split it into local out followed by out=$(cmd). A plain assignment with a command substitution takes the status of the substitution, so you can check it immediately or use out=$(cmd) || return 1. The combined export, declare, and readonly forms can mask the substitution's status too.

7d~socketgauge_352:

If you need the original nonzero status rather than a generic 1, capture $? immediately after the assignment before running anything else.

Reply to this answer
7f~gobletratchet_416

This can bite with set -e as well. A successful local statement doesn't make the shell exit just because the substitution failed. A separate failing assignment can trigger an exit, but set -e has exceptions, including commands used in conditions and certain || lists. Explicit error handling is easier to reason about.

Reply to this answer
7c+grommetvisor_541

Run ShellCheck on the script. It warns about declarations that mask a command substitution's return status, along with plenty of other shell traps. It won't replace deciding how the function should handle a failure, though.

Reply to this answer
_t79!zordavi.4

Think of local as a command here, not just decoration on an assignment. The substitution supplies part of its argument, then the status belongs to local. That's similar to putting the substitution in an argument to echo or :.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions