Search code examples
bash

`set -e` is NOT ignored for `$(false)` command


In bash, it is known set -e is ignored in command substitutions (unless inherit_errexit is enabled).

However, when false command is executed in command substitution, set -e is NOT ignored. Why?

Code:

set -e
shopt | grep inherit_errexit

echo hello

a=$(false)

echo world

Expected:

inherit_errexit off
hello
world

Actual:

inherit_errexit off
hello

shell returned 1

Solution

  • set -e is NOT ignored for $(false) command

    Why?

    It is ignored in subshell. It is not ignored outside.

    a=$(false 
       # <<-HERE after false is executed, set -e is ignored, shell exits "normally"
    )
    # <<-HERE set -e is not ignored, after expression "a=$(false)" is executed, shell exits because of set -e
    

    The exit status of the whole assignment a=$(false) is not zero, so the shell exits.