TExcelTAD
Home › Automation Scripting: Bash, Python & Go › Subshells, Pipelines and Scope

Subshells, Pipelines and Scope

Many "impossible" Bash bugs come from one fact: some code runs in a subshell, a forked copy of the shell. A subshell sees every variable of its parent, but nothing it changes (variables, the current directory, exit, set options) flows back. Knowing exactly where Bash creates subshells explains lost counters, scripts that refuse to exit, and cd commands that seem to do nothing.

Where subshells appear

Construct Runs in a subshell?
( cmds ) yes, on purpose
{ cmds; } no: a group in the current shell
$(cmd) command substitution yes
`cmd1 cmd2`
cmd & yes (a background job)
<(cmd) / >(cmd) process substitution yes, the inner command

( ) vs { }

bash · try it yourself
cat > scope.sh <<'SCRIPT'
set -euo pipefail
mkdir -p build
name="outer"
( cd build; name="changed in ( )"; echo "inside ( ): $PWD, $name" )
echo "after  ( ): $PWD, $name"
{ cd build; name="changed in { }"; }
echo "after  { }: $PWD, $name"
SCRIPT
bash scope.sh
inside ( ): /home/learner/build, changed in ( )
after  ( ): /home/learner, outer
after  { }: /home/learner/build, changed in { }

( cd dir && cmd ) is the idiom for "do this somewhere else without moving the rest of the script". A brace group is for grouping redirections or || without leaving the current shell: { echo a; echo b; } > out.txt.

The lost counter

The most common subshell bug: reading lines in a while loop at the end of a pipeline. The loop runs in a subshell, so the counter it updates disappears when the pipeline ends:

bash · try it yourself
printf 'web-1 up\nweb-2 down\ndb-1 down\n' > hosts.txt

down=0
grep down hosts.txt | while read -r host state; do
  down=$((down + 1))
done
echo "pipeline:              down=$down"

down=0
while read -r host state; do
  [ "$state" = down ] && down=$((down + 1))
done < hosts.txt
echo "redirect:              down=$down"

down=0
while read -r host state; do
  down=$((down + 1))
done < <(grep down hosts.txt)
echo "process substitution:  down=$down"

shopt -s lastpipe
down=0
grep down hosts.txt | while read -r host state; do down=$((down + 1)); done
echo "lastpipe:              down=$down"
pipeline:              down=0
redirect:              down=2
process substitution:  down=2
lastpipe:              down=2

Three fixes, in order of preference:

  1. Redirect the file into the loop (done < file) when you can filter inside the loop.
  2. Feed the loop from a process substitution (done < <(cmd)): the command runs in a subshell, the loop does not.
  3. shopt -s lastpipe runs the last member of a pipeline in the current shell. It only works when job control is off, which is true for scripts but not for interactive shells, so it confuses people testing at the prompt.

exit only leaves the subshell

exit inside a subshell ends that subshell. The parent sees a failed command, which set -e may or may not act on:

bash · try it yourself
cat > check.sh <<'SCRIPT'
set -uo pipefail
check() { [ -f "$1" ] || { echo "missing $1" >&2; exit 1; }; }
config=$( check app.conf; cat app.conf )
echo "1: script continues after exit in \$( ): status $?"
printf 'a.conf\nb.conf\n' | while read -r f; do check "$f"; done
echo "2: script continues after exit in a pipeline: status $?"
check app.conf
echo "3: never printed"
SCRIPT
bash check.sh; echo "-> status $?"
missing app.conf
1: script continues after exit in $( ): status 1
missing a.conf
2: script continues after exit in a pipeline: status 1
missing app.conf
-> status 1

Only the third call, in the main shell, stopped the script; the first two exits only became a non-zero status (the script runs without -e here so you can see them). A die function only dies if it runs in the main shell: keep it out of $( ) and pipelines, or check the status right after them.

Running jobs in parallel, failing correctly

Background jobs are subshells too. wait PID returns that job's exit status, which is how you run several checks in parallel and still fail if any of them failed. Collect the PIDs, then wait for each one in a fixed order:

bash · try it yourself
cat > parallel.sh <<'SCRIPT'
set -euo pipefail
check() {                       # pretend health check: fails for names containing "db"
  sleep 0.2
  case $1 in *db*) echo "$1: FAIL" > "result.$1"; return 1 ;; *) echo "$1: ok" > "result.$1" ;; esac
}
declare -A pids=()
for host in web-1 web-2 db-1; do
  check "$host" & pids[$host]=$!
done
failed=0
for host in web-1 web-2 db-1; do
  if ! wait "${pids[$host]}"; then failed=$((failed + 1)); fi
  cat "result.$host"
done
echo "$failed check(s) failed"
[ "$failed" -eq 0 ]
SCRIPT
bash parallel.sh; echo "-> status $?"
web-1: ok
web-2: ok
db-1: FAIL
1 check(s) failed
-> status 1

Each job writes to its own file, and the results are printed in a fixed order after wait, so the output never interleaves. For many jobs, xargs -P 4 or GNU parallel limit how many run at once. wait with no arguments waits for all jobs but returns 0 even when some failed, so it is the wrong tool for a script that must notice.

Test yourself

Why is down still 0 after grep down hosts.txt | while read …; do down=$((down+1)); done?

  1. read resets variables
  2. The while loop runs in a subshell as part of the pipeline, so its changes are lost
  3. grep fails
  4. Arithmetic does not work in loops

What is the difference between ( cd build; make ) and { cd build; make; }?

  1. None
  2. The parentheses run in a subshell, so the script's directory is unchanged afterwards; the braces change it
  3. Braces run in parallel
  4. Parentheses are faster

How do you make a script fail when one of several background jobs failed?

  1. Call wait with no arguments
  2. Save each job's PID and check wait PID for each one
  3. Use set -e; it covers background jobs
  4. Background jobs cannot fail