Function invocation in for loop does not fail even with "set -e"

Viewed 1077

Consider the following simple bash script:

#!/bin/bash
set -eou pipefail
IFS=$'\n\t'

gen() {
  seq 0 3
}

for c in $(gen); do
  echo c
done

echo "finish"

It has set -e set, so when something fails, it is supposed to just exit with a non-zero exit code.

It will call gen function and prints the output of seq 0 3, will print finish and exit with code=0.

If I modify gen to fail, say, by invoking seqqq command (which doesn't exist) instead:

$ ./script.sh; echo $?
./script.sh: line 6: seqqq: command not found
finish
0

It prints the error message from the sub-shell, it doesn't fail right away and exit (with a non-zero code) immediately as set -e is supposed to do; it keeps executing and exits with code=0.

What is the explanation behind this? Note, if I just replace with my for loop as this, it fails as expected:

#!/bin/bash
set -eou pipefail
IFS=$'\n\t'

gen() {
  seqqq 0 3
}

gen # <-- fails and exits here with code=127

echo "finish"
1 Answers
Related