大于号和小于号必须转义(比较字符串)

大于号和小于号必须转义(比较字符串)

Content #

$ cat bad_string_comparison.sh
#!/bin/bash
# Misusing string comparisons
#
string1=soccer
string2=zorbfootball
#
if [ $string1 > $string2 ]
then
     echo "$string1 is greater than $string2"
else
     echo "$string1 is less than $string2"
fi
$
$ ./bad_string_comparison.sh
soccer is greater than zorbfootball
$
$ ls z*
zorbfootball

这个脚本中只用了大于号,虽然没有出现错误,但结果不对。脚本把大于号解释成了输出重定向,因此创建了一个名为zorbfootball的文件。由于重定向顺利完成了,测试条件返回了退出状态码0,if语句便认为条件成立。

要解决这个问题,需要使用反斜线(\)正确地转义大于号:

$ cat good_string_comparison.sh
#!/bin/bash
# Properly using string comparisons
#
string1=soccer
string2=zorbfootball
#
if [ $string1 \> $string2 ]
then
echo "$string1 is greater than $string2"
else
     echo "$string1 is less than $string2"
fi
$
$ rm -i zorbfootball
rm: remove regular empty file 'zorbfootball'? y
$
$ ./good_string_comparison.sh
soccer is less than zorbfootball
$
$ ls z*
ls: cannot access 'z*': No such file or directory

字符串soccer小于zorbfootball,因为在比较的时候使用的是每个字符的 Unicode编码值。小写字母s的编码值是115,而z的编码值是122。因此,s小于z,进而,soccer小于zorbfootball。

From #

Linux命令行与shell脚本编程大全