標籤:shell
實戰1: 輸入2個整數,判斷大小
三種方式實現:
1 定義變數 2 指令碼傳參 3 read讀入
第一步,給使用者提示,讓其輸入整數
第二步,判斷第一個值和第二個值不為空白
第三步,判斷兩個數為整數
第四步,第一個值與第二個值對比
[[email protected] scripts]# cat test21.sh #!/bin/bashcat <<EOF 1-10... zhengshuEOFread -p "panduan daxiao:" a b[ ${#a} -eq 0 ]&&{ echo "diyigecanshu" exit 1}[ ${#b} -eq 0 ]&&{ echo "diergecanshu" exit 1}expr $a + 1 &>/dev/nullRE_A=$?expr $b + 1 &>/dev/nullRE_B=$?if [ $RE_A -ne 0 -o $RE_B -ne 0 ] then echo "one of you input is not int" exit 1fi if [ $a -eq $b ]; then echo "$a = $b" elif [ $a -gt $b ] then echo "$a > $b" else echo "$a < $b"fi [[email protected] scripts]# sh test2test20.sh test21.sh test2.sh [[email protected] scripts]# sh test21.sh 1-10... zhengshupanduan daxiao:e eone of you input is not int[[email protected] scripts]# sh test21.sh 1-10... zhengshupanduan daxiao:2 342 < 34[[email protected] scripts]# sh test21.sh 1-10... zhengshupanduan daxiao:3 33 = 3[[email protected] scripts]#
指令碼傳參方式實現
我這裡是對上面進行了改變。進到vim裡面
%s#$a#$1#g %s#$b#$2#g 在刪除幾行,就實現了指令碼傳參的方式
[[email protected] scripts]# cat test22.sh #!/bin/bash[ ${#1} -eq 0 ]&&{ echo "diyigecanshu" exit 1}[ ${#2} -eq 0 ]&&{ echo "diergecanshu" exit 1}expr $1 + 1 &>/dev/nullRE_A=$?expr $2 + 1 &>/dev/nullRE_B=$?if [ $RE_A -ne 0 -o $RE_B -ne 0 ] then echo "one of you input is not int" exit 1fi if [ $1 -eq $2 ]; then echo "$1 = $2" elif [ $1 -gt $2 ] then echo "$1 > $2" else echo "$1 < $2"fi [[email protected] scripts]# sh test22.sh 3 done of you input is not int[[email protected] scripts]# sh test22.sh 3 43 < 4[[email protected] scripts]# sh test22.sh 3 33 = 3[[email protected] scripts]#
定義變數的方式
這裡我用以下命令替換了以下原有的變數,進行測試
[[email protected] scripts]# sh test23.sh 3 < 4[[email protected] scripts]# sed -i "s#3#4#g" test23.sh [[email protected] scripts]# sh test23.sh 4 = 4[[email protected] scripts]# sed -i "s#4#dd#g" test23.sh [[email protected] scripts]# sh test23.sh one of you input is not int[[email protected] scripts]# cat test23.sh #!/bin/basha=ddb=dd[ ${#a} -eq 0 ]&&{ echo "diyigecanshu" exit 1}[ ${#b} -eq 0 ]&&{ echo "diergecanshu" exit 1}expr $a + 1 &>/dev/nullRE_A=$?expr $b + 1 &>/dev/nullRE_B=$?if [ $RE_A -ne 0 -o $RE_B -ne 0 ] then echo "one of you input is not int" exit 1fiif [ $a -eq $b ]; then echo "$a = $b" elif [ $a -gt $b ] then echo "$a > $b" else echo "$a < $b"fi [[email protected] scripts]#
本文出自 “晴空” 部落格,謝絕轉載!
Linux-shell之判斷大小