比较 | 描述 | 比较 | 描述 |
str = str2 | 检查str1与str2是否相同 | str > str2 | 检查str1是否大于str2 |
str != str2 | 检查str1与str2是否不同 | -n str | 检查str1的长度是否大于0 |
str < str2 | 检查str1是否小于str2 | -z str | 检查str1的长度是否为0 |
示例1:字符串相同
#!/bin/bash
testuser=root
if [ $USER = $testuser ]
then
echo "Welcome"
else
echo "Sorry ,bye"
fi
[[email protected] ~]# ./test7.sh
Welcome
************************************************
示例2:使用不相等的字符串比较
#!/bin/bash
testuser=bad
if [ $USER != $testuser ]
then
echo "The isn‘t $testuser"
else
echo "Welcome $testuser"
fi
[[email protected] ~]# ./test8.sh
The isn‘t bad
************************************************
示例3:字符串大小
-n 大于0
-z 等于0
#!/bin/bash
var1=testing
var2=‘‘
if [ -n $var1 ]
then
echo "The string is not empty"
else
echo "The string is empty"
fi
if [ -z $var2 ]
then
echo "The string var2 is empty"
else
echo "The string var2 is not empty"
fi
[[email protected] ~]# ./test10.sh
The string is not empty
The string var2 is empty
时间: 2024-10-11 22:10:54