shell腳本學習(2)比較兩個數字大小
阿新 • • 發佈:2017-12-06
$1 num centos7 錯誤 you equal shel 腳本 語句
註意: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: 34 you first number x=34 Please input second number:23 you second number y=23 x greater than y
[zhi@centos7 sh]$ ./number_compare.sh Please input first number: 22 you first number x=22 Please input second number:22 you second number y=22 equal
[zhi@centos7 sh]$ ./number_compare.sh Please input first number: 23 you first number x=23 Please input second number:56 you second number y=56 x less than y
shell腳本學習(2)比較兩個數字大小