Syntax check with bash -n
When Bash reads a script, it must first recognize its grammar. Use bash -n script.sh to parse a file without executing its commands. A zero status indicates successful parsing, not that commands exist or that the program produces the desired result. A missing fi, unmatched quote or missing separator may prevent parsing; the reported line can be later than the real mistake. Start with a small reproducible script and inspect nearby lines. Run syntax checks on each owned file, including modules, because noexec does not execute source commands. Use a fresh directory for these examples. A syntax rejection is only evidence when the intended fixture was successfully written and the parser actually ran. Check setup before running a negative test.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Parse without side effects
printf '%s\n' 'printf "ready\\n" > result.txt' > demo.sh || exit 1bash -n demo.shprintf 'syntax=%s\n' "$?"[[ ! -e result.txt ]] && printf 'no result file\n' Expected stdout:
syntax=0no result fileThe assignment creates demo.sh; bash -n does not create result.txt.
Locate an incomplete condition
printf '%s\n' 'if true; then' ' printf "ok\\n"' > broken.sh || exit 1[[ ! -e diagnostic.txt && ! -L diagnostic.txt ]] || exit 1bash -n broken.sh 2> diagnostic.txtrc=$?[[ $rc == 2 && -f diagnostic.txt && -s diagnostic.txt ]] || exit 1printf 'syntax rejected\n'printf 'diagnostic recorded\n' Expected stdout:
syntax rejecteddiagnostic recordedThe missing fi produces a diagnostic. Check the surrounding grammar instead of relying on exact message text.
Valid grammar, failing command
printf '%s\n' 'exit 7' > demo.sh || exit 1bash -n demo.shprintf 'syntax=%s\n' "$?"bash demo.shprintf 'execution=%s\n' "$?"Expected stdout:
syntax=0execution=7Parsing and execution report different outcomes.
Common mistakes
Do not interpret successful parsing as a successful test. A syntax check does not create output files or execute external tools. A parent script that sources another file still requires a separate syntax check of that file.
Practice
Create one valid script and a second with a missing fi. Predict the status of bash -n for each, then correct the second file. Add a command that fails at runtime to prove that syntax success is insufficient.
Next: Trace with bash -x and PS4