Shell脚本测试命令
我编写以下shell脚本Shell脚本测试命令,shell,design-patterns,testing,scripting,Shell,Design Patterns,Testing,Scripting,我编写以下shell脚本 #! /bin/sh foo=asdfqwer/asdfxv if [ $foo = */* ] then echo bad else echo good fi 在test命令中,我们可以像这样比较字符串和模式 [ string = pattern ] [ string == pattern ] 但是,上面的脚本总是在终端中打印“good”,并且也有如下错误: [ : asdfqwer/asdfxv : unexpected operator
#! /bin/sh
foo=asdfqwer/asdfxv
if [ $foo = */* ]
then
echo bad
else
echo good
fi
在test命令中,我们可以像这样比较字符串和模式
[ string = pattern ]
[ string == pattern ]
但是,上面的脚本总是在终端中打印“good”,并且也有如下错误:
[ : asdfqwer/asdfxv : unexpected operator
有人能告诉我为什么以及如何在shell脚本中比较stirng和模式吗
if [ "$foo" == "*/*" ]
then
echo bad
else
echo good
您需要双等于进行比较,而且字符串比较似乎需要双引号
test命令(或
[
命令)不进行全局比较。相反,shell正在扩展*/*
以匹配目录中的文件,并将其替换到该命令中。可能其中一个文件名作为[
命令的运算符进行解析,并且无效
与globs进行比较的最佳方法是案例
:
#!/bin/sh
foo=asdfqwer/asdfxv
case "$foo" in
*/*) echo bad ;;
*) echo good ;;
esac
我认为它不会起作用,因为只有foo=/结果不好。否则,结果总是好的