写过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 undefined.
Line 11:
str="$strbuzz"
^-- SC2154: strbuzz is referenced but not assigned.
Line 13:
if [[ ! $str ]]
^-- SC2039: In POSIX sh, [[ ]] is undefined.
怎么样,是不是很给力,每个可能的错误都提示了。新手写shell出现莫名的报错时,可以尝试使用奥。当然例子中很多并不是真的错误,而是某种写法不符合POSIX标准,这种情况也应该避免。关于shell的基本内容,也可以参考《shell必备基础知识》。
命令行使用
命令行安装也很简单(记得使用root权限),ubuntu下:
nbsp;apt-get install shellcheck
centos下:
nbsp;yum -y install epel-release
Fedora下:
nbsp;dnf install ShellCheck
使用方法也很简单了:
nbsp;shellcheck myscript.sh
举个例子,下面的写法是新手最容易出错的地方之一:
#!/bin/bash
if[ $# -eq 0 ]
then
echo "no para"
else
echo "$# para"
fi
exit 0
看运行报错:
./test.sh: line 4: if[ 0 -eq 0 ]: command not found
./test.sh: line 5: syntax error near unexpected token `then'
./test.sh: line 5: `then'
只是告诉你在then附近有语法问题,到底什么问题呢?我们用shellcheck看看:
nbsp;shellcheck test.sh
In test.sh line 4:
if[ $# -eq 0 ]
^-- SC1069: You need a space before the [.
这么一看,就很清楚了,原来[前面少了空格。
文章来自公众号