我正在为shell脚本类做一些功课,并且有一个问题要求我编写一个脚本来测试输入的参数是否是有效的shell变量名.以下脚本似乎工作正常.
if echo "$1" | grep -v ".*[^A-Za-z_]" > /dev/null
then
echo yes
else
echo no
fi
我理解括号是BASH shell中测试功能的简写.我的问题是,当我使用括号尝试上述脚本时,我收到了一个错误.
if [ echo "$1" | grep -v ".*[^A-Za-z_]" > /dev/null ]
这个问题(我相信)是grep试图使用]作为其参数,因此在运行脚本时会导致错误.
在什么情况下我不需要括号?
解决方法:
[/ test是一个命令(也是一个内置的),如你所说.它是一个接受特定排序的参数的命令,并且在给定这些参数的情况下以特定方式运行.
它接受标志和比较运算符,并对它们进行操作以获得真或假结果.然后它将该结果转换为返回代码. 0表示true,1表示false.
定义了shell中的if构造
if list; then list; [ elif list; then list; ] … [ else list; ] fi
The if list is executed. If its exit status is zero, the then list is executed. Otherwise, each elif list is executed in turn, and if its exit status is zero, the corresponding then list is executed and the command completes. Otherwise, the else list is executed, if present. The exit status is the exit status of the last command executed, or zero if no condition tested true.
你不需要(也不能使用)[在echo命令/管道周围的原因是因为那不是一组有效的[参数].相反,这是一个命令列表本身,因此,不需要[.您可以直接使用它,并且如果要进行评估,请将管道的返回代码交给它.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。