This question already has an answer here:
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
.
With
bash
you can use-n
:Output:
Since
bash
supports the--posix
options you may runto perform a posix compatible check. I don't know how posixly correct that mode is in detail.
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 prependto 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 usingset -n
. Bash and possibly other shells also support this command-line flag. Therefore you can simply run the following to syntax check your script: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 assh
. Other shells might have similar issues.