如何对便携式POSIX Shell脚本进行语法检查? [英] How to syntax check portable POSIX shell scripts?
问题描述
为第一个参数提供/bin/true
时,以下shell脚本执行良好,但在执行过程中可能会因语法错误而失败!
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
通过静态检查是否可以避免某些语法错误(如果不是全部?)? 如何静态检查给定的 Shell命令语言脚本在语法上有效吗?
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?
Checking for syntax errors in Bash scripts has been answered in this question.
编辑#2:请注意, Bash失败不能正确检查语法是否符合POSIX,甚至在除-n
之外还使用+B
和--posix
标志执行时.
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
.
推荐答案
所有POSIX兼容的 set -n
内置的,可用于检查脚本的语法.因此有可能在前面
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
对您的代码进行语法检查.还请注意,还需要标准 sh 实用程序来支持命令行. -n
标志,具有与使用set -n
等效的语义. Bash和可能的其他Shell也支持此命令行标志.因此,您只需运行以下命令即可对脚本进行语法检查:
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
警告::这不能保证脚本具有完全与POSIX兼容的语法.例如,除了作为sh
调用的-n
之外,即使使用--posix
(和/或+B
)命令行选项时,Bash也会使bashisms(例如数组和c{a,u}t
)不被注意.其他外壳可能也有类似的问题.
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.
这篇关于如何对便携式POSIX Shell脚本进行语法检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!