0
#!/usr/bin/env bash
set -euxo pipefail

echo $(echo "$THIS_VAR_DOES_NOT_EXIST" | cat)

echo "WTF"

Running this script produces:

./wtf.sh 
++ cat
./wtf.sh: line 4: THIS_VAR_DOES_NOT_EXIST: unbound variable
+ echo

+ echo WTF
WTF

Why does it run the last command echo WTF? I assume it would terminate the script at line 4 (due to the presence of set -e).

Does subshells not automatically inherit the set -e option? Or is this some special behaviour?


On the other hand if it seems if I don't echo the command and instead output it to a variable it behaves as expected... What?????

#!/usr/bin/env bash
set -euxo pipefail

echo $(echo "$THIS_VAR_DOES_NOT_EXIST")
echo "this works fine..."

yolo=$(echo "$THIS_VAR_DOES_NOT_EXIST")
echo "this does not"

echo "..."

Produces:

./wtf.sh: line 4: THIS_VAR_DOES_NOT_EXIST: unbound variable
+ echo

+ echo 'this works fine...'
this works fine...
./wtf.sh: line 7: THIS_VAR_DOES_NOT_EXIST: unbound variable
+ yolo=

Why does this behave differently?

  • 1
    What behaviour did you expect? The main shell to exit too when the command substitution runs into an error? – ilkkachu Mar 20 '20 at 13:27
  • 1
    Yes it does inherit it. The subshell will exit when an undefined variable is used (set -u). Exiting a subshell will not exit the main shell though. echo $(exit); echo foo, exit | cat; echo foo, etc will all go on and echo foo. –  Mar 20 '20 at 13:27
  • See https://unix.stackexchange.com/questions/23026/how-can-i-get-bash-to-exit-on-backtick-failure-in-a-similar-way-to-pipefail https://unix.stackexchange.com/questions/256873/error-exit-script-from-within-command-substitution also https://unix.stackexchange.com/questions/217605/bash-how-to-propagate-errors-in-process-substitution https://unix.stackexchange.com/questions/376114/how-to-detect-an-error-using-process-substitution – dave_thompson_085 Mar 20 '20 at 13:34
  • Using a var=$(...) intermediate variable assignment is just the way out of this, because the exit status of such an expression will be that of the command substitution $(...). In echo $(...) the exit status of the command will be that of echo, ie. 0. Try with a=$(exit 13); echo $? vs echo $(exit 13); echo $? –  Mar 20 '20 at 14:34
  • 2

0 Answers0