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


当前回答

我也曾在同样的情况下挣扎过一段时间,下面是我解决的方法:

   if [ "$var1" == "$var2" ]; then
      #dowhateveryouwant
    fi
  

注意比较符号前后的空格,否则将不起作用,或者会得到意想不到的结果。

我花了很多时间在使用一个等号(=)上,但没有用。希望能有所帮助。

其他回答

下面的脚本逐行读取名为“testonthis”的文件,然后将每行与简单字符串、带有特殊字符的字符串和正则表达式进行比较。如果不匹配,脚本将打印该行,否则不打印该行。

在Bash中,空间非常重要。所以下面的方法是可行的:

[ "$LINE" != "table_name" ] 

但下面的情况不会:

["$LINE" != "table_name"] 

所以请用as is:

cat testonthis | while read LINE
do
if [ "$LINE" != "table_name" ] && [ "$LINE" != "--------------------------------" ] && [[ "$LINE" =~ [^[:space:]] ]] && [[ "$LINE" != SQL* ]]; then
echo $LINE
fi
done

我这样做,是兼容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
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和[和]之间的空格很重要 >和<是重定向操作符,因此对于字符串分别使用\>和\<转义。

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

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语句中使用变量

if [ "$x" = "valid" ]; then
  echo "x has the value 'valid'"
fi

如果你想在它们不匹配的时候做一些事情,用!=替换=。您可以在它们各自的文档中阅读更多关于字符串操作和算术操作的信息。

为什么在$x周围使用引号?

你需要在$x周围加上引号,因为如果$x为空,你的Bash脚本会遇到如下所示的语法错误:

if [ = "valid" ]; then

==运算符的非标准使用

请注意,Bash允许使用==与[相等,但这不是标准的。

使用第一种情况,其中$x周围的引号是可选的:

if [[ "$x" == "valid" ]]; then

或者使用第二种情况:

if [ "$x" = "valid" ]; then