How to check the syntax of portable POSIX shell scripts?

The following shell script runs well if /bin/true provided for the first argument, but could otherwise fail with a syntax error at runtime!

 #!/bin/sh if $1 ; then exit; fi /tmp/asdf <<< ASDF # Something with syntax error in POSIX 

Of course, some syntax errors (if not all?) Can be avoided by static checking? How to statically check if a given Shell Command Language script is syntactically valid?

EDIT: Check for syntax errors in Bash scripts was obtained in this question .

EDIT # 2: Note that Bash fails to correctly check if the POSIX syntax adheres even when executed with +B and --posix in addition to -n .

+5
source share
2 answers

All POSIX-compliant Shell Command Language shells support set -n , which can be used to verify script syntax. Therefore, you can add

 set -n 

so that your code syntax checks it. Also note that the standard sh utility is also required to support the -n command line -n , which has equivalent semantics for using set -n , Bash, and possibly other shells also support this command line flag. Therefore, you can simply run the syntax of the following form: script:

 sh -n yourScriptFilename.sh 

WARNING: This does not guarantee you that the script has fully POSIX compatible syntax. For example, Bash allows bahisms (for example, arrays and c{a,u}t ) to go unnoticed even when using the --posix command line (and / or +B ) in addition to -n when calling sh . Other shells may have similar problems.

+6
source

With bash you can use -n :

 bash -n file.sh 

Output:

 a.sh: line 3: syntax error near unexpected token `then' a.sh: line 3: `if then fi # Something with syntax error' 

Since bash supports --posix options you can run

 bash --posix -n file.sh 

to perform posix compatibility check. I do not know how correctly this mode is fixed.

+5
source

All Articles