Strict Mode Set EUO Pipefail Trap
Harden shell scripts with set -euo pipefail and an ERR trap, converting silent failures into loud, traceable exits.
Code
#!/usr/bin/env bash
# 严格模式三件套 + 错误陷阱
set -euo pipefail
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
on_error() {
local exit_code=$?
local line=${BASH_LINENO[0]:-unknown}
echo "Error: 脚本在第 ${line} 行失败,退出码 ${exit_code}" >&2
echo "Error: 执行到此处时的命令:${BASH_COMMAND}" >&2
exit "${exit_code}"
}
trap on_error ERR
# pipefail 演示:管道中段失败不再被吞掉
count_lines() {
grep -c '^data:' "$1" || true # 显式容忍:grep 无匹配返回 1
}
main() {
local input="${SCRIPT_DIR}/events.log"
local lines
lines=$(cat "$input" | wc -l) || return 1
echo "total lines: ${lines}"
echo "data lines: $(count_lines "$input")"
}
main "$@"
How it works
The shebang line is backed by set -euo pipefail: first failure stops the run, unset variables are errors, and a pipeline fails if any stage fails.
The work is delegated to readonly, trap, grep and main, chained through 5 pipes so each stage’s output feeds the next.
3 helper functions (on_error, count_lines and main) keep the repeated logic out of the main flow.
The script leans on parameter expansion 8 times, using forms like ${var:-default} so defaults, trimming, and casing happen inside the shell with no external tool.
A trap handles termination signals so temporary state is cleaned up even on early exit.
Points of care
- The pipeline is 5 stages deep — when it misbehaves, split the pipe and test the stages separately.
Key statements worth quoting
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
grep -c '^data:' "$1" || true # 显式容忍:grep 无匹配返回 1
lines=$(cat "$input" | wc -l) || return 1
Interactive Tools for This Topic
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
- Which external commands does the script rely on?
- `readonly`, `trap`, `grep`, `main` must be available on the PATH environment variable; everything else is shell built-in syntax.
Report a problem with this exampleOpens a pre-filled issue on GitHub.