您的位置:

如何在Shell中判断字符串是否相等和包含

一、什么是Shell

Shell是一种解释型语言,常见的有Bash、Zsh、Ksh等,主要运行于Unix/Linux系统中,也有一些支持Windows平台。

Shell脚本可以运行一系列的命令,也可以用于编写一些简单的程序。

二、字符串比较

Shell中判断字符串是否相等可以使用"="、"=="或"eq"运算符。例如:

if [ "$str1" = "$str2" ]; then
    echo "str1 equals to str2"
fi

if [ "$str1" == "$str2" ]; then
    echo "str1 equals to str2"
fi

if [ "$str1" eq "$str2" ]; then
    echo "str1 equals to str2"
fi

注意:变量的值需要用双引号括起来,否则当变量的值为空时,会报错。

在判断字符串是否不相等时,可以使用"!="、"ne"运算符。

if [ "$str1" != "$str2" ]; then
    echo "str1 is not equal to str2"
fi

if [ "$str1" ne "$str2" ]; then
    echo "str1 is not equal to str2"
fi

三、子串包含判断

判断一个字符串是否包含另一个字符串,可以使用"="、"=="、"!="、"!="运算符配合通配符"*"。例如:

if [ "$str1" = *"hello"* ]; then
    echo "str1 contains hello"
fi

if [ "$str1" == *"hello"* ]; then
    echo "str1 contains hello"
fi

if [ "$str1" != *"world"* ]; then
    echo "str1 does not contain world"
fi

if [ "$str1" != *"world"* ]; then
    echo "str1 does not contain world"
fi

注意:通配符"*"表示任意字符串,可以放在匹配字符串的前面或后面,但是需要用双引号括起来,否则当变量的值为空时,会报错。

四、小结

在Shell中判断字符串是否相等和包含,可以使用"="、"=="、"eq"、"!="、"ne"运算符配合双引号和通配符"*"来实现,同时需要注意双引号的使用和空字符串的判断。