我如何比较一个变量的字符串(并做一些事情,如果他们匹配)?


当前回答

你也可以使用用例/esac:

case "$string" in
 "$pattern" ) echo "found";;
esac

其他回答

你也可以使用用例/esac:

case "$string" in
 "$pattern" ) echo "found";;
esac

我这样做,是兼容Bash和Dash (sh):

testOutput="my test"
pattern="my"

case $testOutput in (*"$pattern"*)
    echo "if there is a match"
    exit 1
    ;;
(*)
   ! echo there is no coincidence!
;;esac

你是否存在比较问题?(如下面?)

var="true"
if [[ $var == "true" ]]; then
  # It should be working, but it is not...
else
  # It is falling here...
fi

试试=~操作符(正则表达式操作符),它可能会工作:

var="true"
if [[ $var =~ "true" ]];then
  # Now it works here!!
else
  # No more inequality
fi

Bash正则表达式运算符=~(官方参考) StackOverflow的进一步示例(此处)

要比较字符串和通配符,使用:

if [[ "$stringA" == *"$stringB"* ]]; then
  # Do something here
else
  # Do something here
fi
a="abc"
b="def"

# Equality Comparison
if [ "$a" == "$b" ]; then
    echo "Strings match"
else
    echo "Strings don't match"
fi

# Lexicographic (greater than, less than) comparison.
if [ "$a" \< "$b" ]; then
    echo "$a is lexicographically smaller then $b"
elif [ "$a" \> "$b" ]; then
    echo "$b is lexicographically smaller than $a"
else
    echo "Strings are equal"
fi

注:

if和[和]之间的空格很重要 >和<是重定向操作符,因此对于字符串分别使用\>和\<转义。