Testing bash Script Syntax
Problem
You are editing a bash script and want to make sure that your syntax is correct.
Solution
Use the -n argument to
bash to test syntax often, ideally after every
save, and certainly before committing any changes to a revision control
system:
$ bash -n my_script $ $ echo 'echo "Broken line' >> my_script $ bash -n my_script my_script: line 4: unexpected EOF while looking for matching `"' my_script: line 5: syntax error: unexpected end of file
Discussion
The -n option is tricky to find
in the bash manpage or other reference material
since it’s located under the set built-in. It is
noted in passing in bash --help for
-D, but it is never explained there.
This flag tells bash to “read commands but do not
execute them,” which of course will find bash
syntax errors.
As with all syntax checkers, this will not catch logic errors or syntax errors in other commands called by the script.
See Also
man bash
bash --help
bash -c “help set”
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access