The best answers to the question “How do I syntax check a Bash script without running it?” in the category Dev.
Is it possible to check a bash script syntax without executing it?
Using Perl, I can run
perl -c 'script name'. Is there any equivalent command for bash scripts?
Time changes everything. Here is a web site which provide online syntax checking for shell script.
I found it is very powerful detecting common errors.
ShellCheck is a static analysis and linting tool for sh/bash scripts. It’s mainly focused on handling typical beginner and intermediate level syntax errors and pitfalls where the shell just gives a cryptic error message or strange behavior, but it also reports on a few more advanced issues where corner cases can cause delayed failures.
Haskell source code is available on GitHub!
bash -n scriptname
Perhaps an obvious caveat: this validates syntax but won’t check if your bash script tries to execute a command that isn’t in your path, like
ech hello instead of
sh -n script-name
Run this. If there are any syntax errors in the script, then it returns the same error message.
If there are no errors, then it comes out without giving any message. You can check immediately by using
echo $?, which will return
0 confirming successful without any mistake.
It worked for me well. I ran on Linux OS, Bash Shell.
I also enable the ‘u’ option on every bash script I write in order to do some extra checking:
This will report the usage of uninitialized variables, like in the following script ‘check_init.sh’
#!/bin/sh set -u message=hello echo $mesage
Running the script :
Will report the following :
./check_init.sh: mesage: Parameter not set.
Very useful to catch typos