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”
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.