When a script misbehaves: tracing, syntax checks, safe input and portability to dash
Debug a script that fails under /bin/sh and then silently reads nothing under Bash: reproduce with the real interpreter, check syntax per shell, list bashisms with ShellCheck, trace with a PS4 that survives root, fix the quoting, read and print safely, and port to POSIX sh when Bash may be missing.
Contentsand lesson path
On this page
- The problem
- Step 1: Reproduce the failure the way the server runs it
- Step 2: Check the syntax without running anything
- Step 3: List every Bash-only construct at once
- Step 4: Decide: require Bash, or port to POSIX sh?
- Step 5: Trace it, with line numbers that survive root
- Step 6: Fix the quoting, check, and re-run
- Step 7: Read safely, print safely, and the POSIX version
- Check your understanding
- Apply it
- Review prompt
Lessons of Advanced Shell & Text Processing
- Patterns that travel: regular expressions in grep, sed and awk Concept · 25 min
- Lab: from a raw access log to a report with grep, sed and awk Lab · 30 min
- Bash beyond the basics: expansions, arrays, here-documents and process substitution Worked example · 25 min
- When a script misbehaves: tracing, syntax checks, safe input and portability to dash Worked example · 20 min
- Lab: living on a remote server - editors, sudoedit, startup files, job control and tmux Lab · 30 min
- Check: shell fluency tasks and a log-report script to repair Knowledge check · 10 questions
What you will learn
- Trace and debug scripts with set -x, PS4 and bash -n, read input safely with read and format output with printf, and identify Bash-only syntax that breaks under POSIX sh (dash).
Prerequisites: Scripting Basics
01. The problem
A teammate wrote top-clients.sh, which prints the busiest client addresses in a log directory. On the Ubuntu servers it fails when cron runs it, and on the archive server, where logs live in logs archive/, it prints errors and still exits 0. You have to find out why, fix it, and decide how portable it must be. The constraints:
- The script will run on Ubuntu and Debian servers, where
/bin/shis dash, a small POSIX shell, not Bash. - It may also have to run in minimal container images that have no Bash at all.
This builds on quoting, strict mode and ShellCheck and on the shebang line from anatomy of a script. Tested on Debian 13 with bash 5.2.37, dash 0.5.12 and ShellCheck 0.11.0 (the 0.10.0 Debian package gives the same findings), inside a container where you are root, which matters in step 5. Create the test data first: copy the three files from the access-log lab into a directory called logs archive, then save the script exactly as your teammate wrote it.
mkdir -p 'logs archive' && cp logs/access.log* 'logs archive/'
cat > top-clients.sh <<'EOF'
#!/bin/sh
# top-clients.sh [DIR] [N]: the N busiest client addresses in DIR's logs
dir=${1:-./logs}
n=${2:-3}
files=($dir/access.log*)
count_ips() {
zcat -f "$@" | awk '{ print $1 }' | sort | uniq -c | sort -k1,1nr -k2 | head -n "$n"
}
if [[ ${#files[@]} -eq 0 ]]; then echo "no logs in $dir" >&2; exit 1; fi
count_ips ${files[@]}
EOF
chmod +x top-clients.sh02. Step 1: Reproduce the failure the way the server runs it
Run it with ./top-clients.sh, not bash top-clients.sh. The first form lets the kernel read the shebang, #!/bin/sh, and start dash; the second ignores the shebang and starts Bash, which hides the bug. Reproducing under the same interpreter as production is the first rule of debugging a script.
./top-clients.sh 'logs archive'; echo "rc=$?"./top-clients.sh: 5: Syntax error: "(" unexpected
rc=2Dash reports the script name and line 5, where files=(…) creates an array; POSIX sh has no arrays, so to dash this is broken grammar. That does not mean nothing ran. Dash, like Bash, reads and runs a script one command at a time: the assignments on lines 3 and 4 ran before it reached line 5. A rm above the error would have run too, which is why step 2 checks the syntax without running anything.
printf '%s\n' 'echo "line 1 ran"' 'files=(a b)' 'echo "line 3 ran"' > probe.sh
dash probe.sh; echo "rc=$?"line 1 ran
probe.sh: 2: Syntax error: "(" unexpected
rc=203. Step 2: Check the syntax without running anything
bash -n and dash -n read a script and report syntax errors without executing a single command, safe even for scripts that delete things. Each checks against its own grammar. Predict: which of the two commands below reports an error?
bash -n top-clients.sh; echo "bash -n rc=$?"
dash -n top-clients.sh; echo "dash -n rc=$?"bash -n rc=0
top-clients.sh: 5: Syntax error: "(" unexpected
dash -n rc=2bash -n is happy because the file is valid Bash. A syntax check only answers "valid for which shell?" Note also what neither check can find: [[ on line 9 is not a syntax error to dash, just a command name, and it would fail only when that line runs (as [[: not found).
04. Step 3: List every Bash-only construct at once
Dash stops at the first error, so fixing errors one by one is slow. ShellCheck reads the shebang, assumes POSIX sh, and reports every construct that sh does not define, plus quoting bugs. -f gcc prints one finding per line.
shellcheck -f gcc top-clients.sh |
sed -E 's/^[^:]+:([0-9]+):[0-9]+: [a-z]+: (.*) \[(SC[0-9]+)\]$/line \1 \3: \2/' |
cut -c1-76line 5 SC3030: In POSIX sh, arrays are undefined.
line 5 SC2206: Quote to prevent word splitting/globbing, or split robustly w
line 9 SC3010: In POSIX sh, [[ ]] is undefined.
line 10 SC2068: Double quote array expansions to avoid re-splitting elements
line 10 SC3054: In POSIX sh, array references are undefined.The SC3xxx findings are portability problems. SC2206 and SC2068 are different: they are quoting bugs that would break the script even under Bash. Keep that second group in mind for step 5.
05. Step 4: Decide: require Bash, or port to POSIX sh?
There are two honest fixes, and the constraints decide between them.
- Require Bash. Change the shebang to
#!/usr/bin/env bash. Cheap and safe when every target has Bash, as Debian and Ubuntu servers do. You keep arrays and[[. - Port to POSIX sh. Rewrite the Bash-only parts. Needed when the script must run where Bash may be missing, such as Alpine-based images or embedded systems, or when a policy says scripts in
/etchooks must besh.
Running it as bash top-clients.sh in cron only moves the problem: the script still says #!/bin/sh, so the next person who runs ./top-clients.sh hits the same error. Take the cheap fix now; step 7 does the port. Predict: with Bash as the interpreter, will the script now print the right answer?
sed -i '1s|.*|#!/usr/bin/env bash|' top-clients.sh
./top-clients.sh 'logs archive'; echo "rc=$?"gzip: logs is a directory -- ignored
gzip: archive/access.log*.gz: No such file or directory
rc=0It runs, but it reads no data and reports success. The exit status is 0 because the status of a pipeline is that of its last command, head, which succeeded on empty input. This is the second bug from the problem statement, and the most dangerous kind: wrong output with a success code.
06. Step 5: Trace it, with line numbers that survive root
set -x (or bash -x) makes Bash print each command after expansion, prefixed with the value of PS4. The default prefix is + . A prefix with the file, line and function, such as '+ ${BASH_SOURCE##*/}:${LINENO}:${FUNCNAME[0]:-main}: ', tells you where each traced command came from. The single quotes matter: PS4 is expanded again for every trace line.
Since bash 4.4, a shell running as root does not import PS4 from the environment, a guard against a security hole in PS4 expansion. So PS4=… bash -x script works for a normal user and silently falls back to + for root. A robust way is BASH_ENV: a non-interactive Bash reads the file it names before running the script, so the file can set PS4 and turn on tracing.
id -un
PS4='+ L${LINENO}: ' bash -x ./top-clients.sh 'logs archive' 2>&1 | head -n 2
cat > debug.env <<'EOF'
PS4='+ ${BASH_SOURCE##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
set -x
EOF
BASH_ENV=./debug.env ./top-clients.sh 'logs archive' 2>&1 | head -n 5root
+ dir='logs archive'
+ n=3
+ top-clients.sh:3:main: dir='logs archive'
+ top-clients.sh:4:main: n=3
+ top-clients.sh:5:main: files=($dir/access.log*)
+ top-clients.sh:9:main: [[ 2 -eq 0 ]]
+ top-clients.sh:10:main: count_ips logs 'archive/access.log*'Line 9 says the array has 2 elements, although the directory holds 3 files. Line 10 shows why: the unquoted $dir was split at the space into logs and archive/access.log*, and the second word, matching no file, stayed a literal pattern. SC2206 warned about exactly this. If the directory name had no space, the bug would stay hidden; changing that one condition is what exposes it.
To keep the trace apart from the script's real error messages, send it to another file descriptor with BASH_XTRACEFD, for example exec 9>trace.log; BASH_XTRACEFD=9 before set -x.
07. Step 6: Fix the quoting, check, and re-run
Quote the expansion where the array is built and where it is used. Turn on nullglob, or the empty-directory check can never fire: an unmatched glob stays as one word. Add set -o pipefail so a failing zcat gives a failing exit status, and end the pipeline with awk -v n="$n" 'NR <= n' instead of head; the second block below shows why.
cat > top-clients.sh <<'EOF'
#!/usr/bin/env bash
# top-clients.sh [DIR] [N]: the N busiest client addresses in DIR's logs
set -o pipefail
shopt -s nullglob
dir=${1:-./logs}
n=${2:-3}
files=("$dir"/access.log*)
count_ips() {
zcat -f "$@" | awk '{ print $1 }' | sort | uniq -c | sort -k1,1nr -k2 |
awk -v n="$n" 'NR <= n'
}
if [[ ${#files[@]} -eq 0 ]]; then echo "no logs in $dir" >&2; exit 1; fi
count_ips "${files[@]}"
EOF
shellcheck top-clients.sh && echo 'shellcheck: no findings'
./top-clients.sh 'logs archive'; echo "rc=$?"
mkdir -p empty; ./top-clients.sh empty; echo "rc=$?"shellcheck: no findings
7 203.0.113.7
6 192.0.2.55
5 198.51.100.23
rc=0
no logs in empty
rc=1Why not head? head -n 3 exits after three lines. If sort still has output to write, its next write to the closed pipe raises SIGPIPE, whose default action kills it, and Bash reports a death by signal 13 as 128 + 13 = 141. Without pipefail nobody notices, because the pipeline's status is head's 0. With it, the pipeline fails, and under set -e the script stops without a message. It is a race, not a size limit: small outputs often pass because sort finished writing before head exited. In our container, 200 runs with 500 clients (9 KB of output, far below the 64 KiB pipe buffer) failed 12 times, and with 1,000 clients 188 times.
After a sort, reading to the end costs little, because sort has read all its input before printing its first line. To peek at the start of a huge or endless stream (zcat big.gz | head, tail -f), keep head and run that pipeline without pipefail.
mkdir -p big
awk 'BEGIN { for (i = 0; i < 30000; i++)
printf "10.0.%d.%d [26/Nov/2026:09:00:00 +0000] \"GET / HTTP/1.1\" 200 1 0.001\n",
i / 256, i % 256 }' > big/access.log
set -o pipefail
awk '{ print $1 }' big/access.log | sort | uniq -c | sort -k1,1nr -k2 |
head -n 3 > /dev/null
echo "with head: rc=$? stages=${PIPESTATUS[*]}"
awk '{ print $1 }' big/access.log | sort | uniq -c | sort -k1,1nr -k2 |
awk -v n=3 'NR <= n' > /dev/null
echo "with awk: rc=$? stages=${PIPESTATUS[*]}"
./top-clients.sh big > /dev/null; echo "fixed script: rc=$?"
set +o pipefailwith head: rc=141 stages=0 0 0 141 0
with awk: rc=0 stages=0 0 0 0 0
fixed script: rc=008. Step 7: Read safely, print safely, and the POSIX version
Two habits make any shell script more robust. To read lines exactly as written, use while IFS= read -r line: plain read strips leading and trailing spaces and treats backslashes as escape characters. To print data, use printf '%s\n' "$var" rather than echo: dash's echo interprets backslash sequences such as \t, while Bash's does not by default, so echo output can differ between the two shells.
printf ' 192.0.2.55 # scanner\nC:\\new\\temp\n' > skip.txt
while read line; do printf '[%s]\n' "$line"; done < skip.txt
while IFS= read -r line; do printf '[%s]\n' "$line"; done < skip.txt
dash -c 'echo "C:\temp\new"'; dash -c 'printf "%s\n" "C:\temp\new"'[192.0.2.55 # scanner]
[C:newtemp]
[ 192.0.2.55 # scanner]
[C:\new\temp]
C: emp
ew
C:\temp\newIf the script must also run where there is no Bash, port it. POSIX sh has exactly one list that keeps elements intact: the positional parameters, "$@". set -- empties them and set -- "$@" "$f" appends a file. [ … ] replaces [[ … ]], and a case pattern validates that N is a number. set -o pipefail was added to POSIX in the 2024 edition and Debian 13's dash accepts it, but ShellCheck (0.10 and 0.11) still reports it as undefined in sh (SC3040), and an older sh may reject it. The script records that choice in a shellcheck disable comment; on older systems, leave pipefail out.
cat > top-clients-posix.sh <<'EOF'
#!/bin/sh
# top-clients.sh [DIR] [N]: the N busiest client addresses in DIR's logs (POSIX sh)
# shellcheck disable=SC3040 # pipefail: in POSIX.1-2024, still flagged by ShellCheck
set -o pipefail
dir=${1:-./logs}
n=${2:-3}
case $n in
'' | *[!0-9]*) printf 'N must be a number, got "%s"\n' "$n" >&2; exit 2 ;;
esac
set -- # the positional parameters hold the file list
for f in "$dir"/access.log*; do
[ -e "$f" ] && set -- "$@" "$f"
done
if [ "$#" -eq 0 ]; then printf 'no logs in %s\n' "$dir" >&2; exit 1; fi
zcat -f -- "$@" | awk '{ print $1 }' | sort | uniq -c | sort -k1,1nr -k2 |
awk -v n="$n" 'NR <= n'
EOF
chmod +x top-clients-posix.sh
dash -n top-clients-posix.sh && shellcheck top-clients-posix.sh && echo 'checks: OK'
./top-clients-posix.sh 'logs archive' 2; echo "rc=$?"
./top-clients-posix.sh 'logs archive' x; echo "rc=$?"
./top-clients-posix.sh big > /dev/null; echo "rc=$?"checks: OK
7 203.0.113.7
6 192.0.2.55
rc=0
N must be a number, got "x"
rc=2
rc=009. Check your understanding
10. Apply it
Take your logreport.sh from the previous lesson's practice task and make it pass four gates: bash -n, ShellCheck with no findings, a run on a log directory whose name contains a space, and exit status 0 on the 30,000-client log from step 6. Record one traced run, with the step 5 PS4 prefix, in a file through BASH_XTRACEFD, and submit it with the script. Then write two sentences for your team: does logreport.sh require Bash, and why is that acceptable (or not) for the servers it will run on?
11. Review prompt
Without looking back, explain why bash -n passed and ./top-clients.sh failed, and why the Bash version then exited 0 with no data. Describe how you would get line numbers in a trace when you are root, and name three Bash constructs that dash rejects along with their POSIX replacements.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.