brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: bash -n checks a script for syntax errors without running it

Bash
~/tips/tip-shell-bash-n-syntax-check

bash -n backup.sh && echo "syntax ok"

Parses a script and reports syntax errors without executing a single command.

When a script deletes things or restarts containers, I do not want the first test of it to be a real run. There is a flag that only reads.

bash -n reads the commands but does not execute them. The manual says it can be used to check a script for syntax errors, so it catches an unclosed quote, a missing fi or a stray parenthesis:

bash -n backup.sh && echo "syntax ok"

No output and exit code 0 means the parser is happy. Otherwise it prints the line where it gave up. For an unclosed if or quote that is usually the end of the file, so the real mistake is above the reported line. With a one-line file containing only if true; then, bash 5.2 here reports an unexpected end of file on line 2, which does not exist.

It also works as a quick check in a loop over a whole folder of scripts:

for f in /mnt/user/appdata/<app>/scripts/*.sh; do bash -n "$f" || echo "problem in $f"; done

The limit is what a parser can see. A mistyped command name, a wrong path or an unset variable is fine as far as syntax goes and only shows up when the script runs. For those I would add shellcheck, which looks at the code in more depth. The same check exists inside a script as set -n, but the manual says interactive shells ignore it, so do not try it at the prompt: typing set -n there does nothing.

Further reading: bash(1) manual page

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link