我编写了以下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
有人能告诉我为什么以及如何比较shell脚本中的搅拌和模式?
答案 0 :(得分:1)
test
命令(或[
命令)不进行全局比较。相反,shell正在扩展*/*
以匹配目录中的文件,并将它们替换为该命令。据推测,其中一个文件名被解析为[
命令的运算符,并且无效。
与全球比较的最佳方式是case
:
#!/bin/sh
foo=asdfqwer/asdfxv
case "$foo" in
*/*) echo bad ;;
*) echo good ;;
esac
答案 1 :(得分:0)
if [ "$foo" == "*/*" ]
then
echo bad
else
echo good
你需要双等于比较,看起来像字符串比较需要双引号。
http://www.tech-recipes.com/rx/209/bournebash-shell-scripts-string-comparison/