注意:shell中对比字符串只能使用==、<、>、!=、-z、-n。对比字符串时,末尾一定要加上x(或者a、b等)一个字符,因为if [ $1x == "ab"x ]时如果没有了x ,并且$1是"",这个语句会翻译成if [ == "ab" ],左边相当于没有东西了,会报语法错误。或者使用[[ ]],就不需要x了。使用<或者>时,如果是用[ ],需要用转义符"\",如\>。
对比数字使用既能使用-eq、-ne、-gt、-ge、-lt、-le,也能使用==、<、>、!=。其中-eq的意思是equal,-ne是unequal,-gt是greater than,-ge是greater than or equal to,-lt是less than,-le是less than or equal to。
[zhi@centos7 sh]$ cat number_compare.sh
#!/bin/bash
#脚本名称:number_compare.sh
#用途:比较二个数字大小
echo " Please input first number:"
read x
echo "you first number x=$x"
read -p " Please input second number:" y
echo "you second number y=$y" if [ $x -eq $y ];then
echo "equal"
elif [ $x -gt $y ];then
echo "x greater than y"
else
echo "x less than y"
fi
运行测试:
[zhi@centos7 sh]$ ./number_compare.sh
Please input first number: you first number x=
Please input second number:
you second number y=
x greater than y
[zhi@centos7 sh]$ ./number_compare.sh
Please input first number: you first number x=
Please input second number:
you second number y=
equal
[zhi@centos7 sh]$ ./number_compare.sh
Please input first number: you first number x=
Please input second number:
you second number y=
x less than y