TExcelTAD
Home › Automation Scripting: Bash, Python & Go › Strict Mode and Its Traps

Strict Mode and Its Traps

Exit Codes & Error Handling in the Linux course introduced set -euo pipefail: stop at the first failing command, treat unset variables as errors, and let a failure anywhere in a pipeline count. That header belongs at the top of every script. It is also not a guarantee. errexit has a long list of situations where Bash deliberately ignores a failure, and a few where it stops a script that did nothing wrong. This lesson walks through the ones that bite in real scripts.

Trap 1: functions called as a condition

set -e is switched off for any command that is part of a condition: in if, while, after !, and on the left of && or ||. That includes everything inside a function you call there:

bash · try it yourself
cat > deploy.sh <<'SCRIPT'
set -euo pipefail
deploy() {
  cp release.tar.gz /srv/releases/      # fails: no such file
  echo "deploy: marked as done"
}
if deploy; then
  echo "result: deploy succeeded"
fi
deploy && echo "result: second call succeeded"
SCRIPT
bash deploy.sh; echo "exit status: $?"
cp: cannot stat 'release.tar.gz': No such file or directory
deploy: marked as done
result: deploy succeeded
cp: cannot stat 'release.tar.gz': No such file or directory
deploy: marked as done
result: second call succeeded
exit status: 0

The cp failed twice, and both times the function carried on and returned the status of its last command, echo, which succeeded. Inside a condition, a function needs explicit checks: cp … || return 1. The safe habit is to call work functions as plain statements and test their result afterwards only when you must.

Trap 2: local and export hide the status

local var=$(cmd) runs two commands: the substitution and local. The status that set -e sees is local's, and local succeeds:

bash · try it yourself
cat > version.sh <<'SCRIPT'
set -euo pipefail
read_version() {
  local v=$(cat VERSION)          # cat fails, local succeeds
  echo "version is '$v'"
  local w
  w=$(cat VERSION)                # this one stops the script
  echo "never printed"
}
read_version
SCRIPT
bash version.sh; echo "exit status: $?"
cat: VERSION: No such file or directory
version is ''
cat: VERSION: No such file or directory
exit status: 1

Declare first, assign second. The same applies to export VAR=$(cmd) and readonly VAR=$(cmd). ShellCheck reports this as SC2155.

Trap 3: command substitution inside another command

A substitution whose result is used by another command does not stop the script either:

bash · try it yourself
cat > sub.sh <<'SCRIPT'
set -euo pipefail
echo "host: $(cat hostname.txt)"
echo "still running"
shopt -s inherit_errexit
host=$(cat hostname.txt; echo "fallback")
echo "host is $host"
SCRIPT
bash sub.sh; echo "exit status: $?"
cat: hostname.txt: No such file or directory
host:
still running
cat: hostname.txt: No such file or directory
exit status: 1

The first cat failed inside echo "…$(…)" and the script went on with an empty string. Assigning to a variable on its own line (host=$(…)) makes the substitution's status count. By default the commands inside $(…) do not run with errexit, so the second substitution would have printed fallback; shopt -s inherit_errexit (Bash 4.4 and later) makes them inherit it, and the substitution stops at the failing cat.

Trap 4: arithmetic that evaluates to zero

(( expr )) returns status 1 when the expression's value is 0. Post-increment returns the old value, so the first ((count++)) on a counter that starts at 0 kills the script:

bash · try it yourself
cat > count.sh <<'SCRIPT'
set -euo pipefail
count=0
for f in a b c; do
  ((count++))
  echo "counted $f"
done
SCRIPT
bash count.sh; echo "exit status: $?"
cat > count2.sh <<'SCRIPT'
set -euo pipefail
count=0
for f in a b c; do
  count=$((count + 1))
done
echo "count=$count"
SCRIPT
bash count2.sh
exit status: 1
count=3

Use count=$((count + 1)) (an assignment, always status 0), or ((++count)) when you know the value is never 0.

Trap 5: pipefail and early readers

With pipefail, a pipeline fails if any member fails, and that includes a writer killed because its reader stopped early. head exits after one line; the writer then gets SIGPIPE (status 141 = 128 + 13):

bash · try it yourself
set -o pipefail
seq 1 100000 | head -n 1
echo "status: $?"
grep -c ERROR /dev/null | head -n 1
echo "status: $?"
{ seq 1 100000 || true; } | head -n 1
echo "status: $?"
1
status: 141
0
status: 1
1
status: 0

Two different problems show up here:

  • seq was killed by SIGPIPE. Whether that happens depends on how much output is buffered, so the same script can pass with 10 lines and fail with 100,000. When you only need the first lines, wrap the writer ({ cmd || true; }) or let the tool limit itself (grep -m 1, jq 'first(...)', awk 'NR==1{print; exit}').
  • grep found nothing and returned 1, as it is designed to. "No matches" is not an error for your script, so say so: { grep -c ERROR log || true; }.

Trap 6: set -u and optional values

set -u turns a typo into an error, but it also fires for values that are allowed to be missing: optional arguments and environment variables. Give those a default explicitly:

bash · try it yourself
cat > greet.sh <<'SCRIPT'
set -euo pipefail
name=${1:-world}               # optional positional argument
level=${LOG_LEVEL:-info}       # optional environment variable
echo "hello, $name (log level $level)"
echo "required: $DEPLOY_ENV"
SCRIPT
bash greet.sh; echo "exit status: $?"
LOG_LEVEL=debug DEPLOY_ENV=staging bash greet.sh Ada
hello, world (log level info)
greet.sh: line 5: DEPLOY_ENV: unbound variable
exit status: 1
hello, Ada (log level debug)
required: staging

For a required variable, : "${DEPLOY_ENV:?must be set}" at the top of the script fails early with your own message.

What strict mode is, then

set -euo pipefail is a safety net with holes, not error handling. Use it, and also:

Do Instead of
`cmd
local x; x=$(cmd) local x=$(cmd)
var=$(cmd) on its own line, then use $var echo "$(cmd)"
n=$((n + 1)) ((n++))
`{ grep …
${VAR:-default} / ${VAR:?message} bare $VAR for optional or required settings

Test yourself

A function contains a failing cp and is called as if deploy; then …. With set -e, what happens?

  1. The script stops at cp
  2. set -e is ignored inside the function because it runs as a condition, so it continues
  3. Bash prints a syntax error
  4. The if branch is skipped and the script exits

Why does local v=$(cat missing) not stop a set -e script?

  1. cat never fails
  2. The status checked is that of local, which succeeds
  3. local is not allowed in functions
  4. Command substitution is disabled under set -u

Under set -e, why does count=0; ((count++)) stop the script?

  1. count is unset
  2. Post-increment evaluates to the old value 0, and (( )) returns status 1 for 0
  3. Arithmetic is not allowed with set -e
  4. ++ only works in for loops