来源:公众号【编程珠玑】
作者:守望先生
ID:shouwangxiansheng
写过shell脚本的人都知道,即便出现一些简单的语法错误,运行的时候也可能没有办法发现。有些看似运行正确的脚本,实际上可能在某些分支,某些场景下仍然出现错误,而有的写法可能运行正常,但是却不符合POSIX标准,不具备可移植性。
诚然,shell脚本是解释运行,没有办法向C/C++那样严格检查,但是我们仍然可以借助一些工具帮助我们提前发现一些错误。
shellcheck
shellcheck就是这样的一个工具。它可以在多种场景下使用,包括在线,命令行检查,编辑器配置,下面逐一介绍。
在线使用
顾名思义,它提供了一个在线的检查地址,https://www.shellcheck.net/,进入网址即可使用。
例如,你输入你的脚本内容:
#!/bin/sh
for n in {1..$RANDOM}
do
str=""
if (( n % 3 == 0 ))
then
str="fizz"
fi
if [ $[n%5] == 0 ]
then
str="$strbuzz"
fi
if [[ ! $str ]]
then
str="$n"
fi
echo "$str"
done
shell
它会给出错误提示或者建议:
Line 2:
for n in {1..$RANDOM}
^-- SC2039: In POSIX sh, brace expansion is undefined.
^-- SC2039: In POSIX sh, RANDOM is undefined.
Line 5:
if (( n % 3 == 0 ))
^-- SC2039: In POSIX sh, standalone ((..)) is undefined.
Line 9:
if [ $[n%5] == 0 ]
^-- SC2039: In POSIX sh, $[..] in place of $((..)) is undefined.
^-- SC2007: Use $((..)) instead of deprecated $[..]
^-- SC2039: In POSIX sh, == in place of = is undefi