How to syntax check portable POSIX shell scripts?

2019-03-21 03:20发布

问题:

This question already has an answer here:

  • How do I syntax check a Bash script without running it? 7 answers

The following shell script executes well when provided /bin/true for the first argument, but may otherwise fail with a syntax error during execution!

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

Surely some syntax errors (if not all?) can be avoided by static checking? How do I statically check whether a given Shell Command Language script is syntactically valid?

EDIT: Checking for syntax errors in Bash scripts has been answered in this question.

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

回答1:

All POSIX-compatible Shell Command Language shells support the set -n built-in which can be used to check the syntax of the script. Therefore it is possible to prepend

set -n

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

sh -n yourScriptFilename.sh

WARNING: This does not give you a guarantee that the script has fully POSIX compatible syntax. For example, Bash allows bashisms (e.g. arrays and c{a,u}t) to go unnoticed even when using the --posix (and/or +B) command line option in addition to -n when invoked as sh. Other shells might have similar issues.



回答2:

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 the --posix options you may run

bash --posix -n file.sh

to perform a posix compatible check. I don't know how posixly correct that mode is in detail.