Shell 字符串运算范例
2021-08-31 09:27 更新
下面是一个例子,它使用的所有字符串运算:
#!/bin/sh
a="abc"
b="efg"
if [ $a = $b ]
then
echo "$a = $b : a is equal to b"
else
echo "$a = $b: a is not equal to b"
fi
if [ $a != $b ]
then
echo "$a != $b : a is not equal to b"
else
echo "$a != $b: a is equal to b"
fi
if [ -z $a ]
then
echo "-z $a : string length is zero"
else
echo "-z $a : string length is not zero"
fi
if [ -n $a ]
then
echo "-n $a : string length is not zero"
else
echo "-n $a : string length is zero"
fi
if [ $a ]
then
echo "$a : string is not empty"
else
echo "$a : string is empty"
fi
这将产生以下输出结果:
abc = efg: a is not equal to b
abc != efg : a is not equal to b
-z abc : string length is not zero
-n abc : string length is not zero
abc : string is not empty
要注意以下几点:
- 运算符和表达式之间必须有空格,例如2+2是不正确的,因为它应该写成2 + 2.
- if...then...else...fi 语句在下一章节中已经解释的决策声明。
以上内容是否对您有帮助:
更多建议: