#!/bin/bash read -p "pls input two number:" a b if [ ! -z $b ] then expr $a + $b &>/dev/null if [ $? -eq 0 ] then echo "a-b=$(($a-$b))" echo "a+b=$(($a+$b))" echo "a*b=$(($a*$b))" echo "a/b=$(($a/$b))" else echo "input is not zhengshu" fi else echo "you must input two number" fi
執行結果如下:輸入字母會報錯,輸入不是整數;只輸入1個參數也會報錯;
[baby@localhost ~]$ sh a.sh pls input two number:4 2 a-b=2 a+b=6 a*b=8 a/b=2 [baby@localhost ~]$ sh a.sh pls input two number:a 2 input is not zhengshu [baby@localhost ~]$ sh a.sh pls input two number:10 you must input two number
腳本有bug,如果輸入3個參數的話會報錯如下: [baby@localhost ~]$ sh a.sh pls input two number:1 3 3 a.sh: line 3: [: 3: binary operator expected you must input two number 針對上面的腳本bug修改如下: 思路為:多添加一個變量c,並多了if判斷,先判斷$a是否為空,如為空提示輸入2個數字並退出;然後判斷$b是否為空,如未空提示輸入2個數字並退出;只有$a $b都不為空即都有輸入值,再判斷$c是否為空,如未空執行下面的整數判斷,如$c不為空同樣提示輸入2個數字並退出;
#!/bin/bash read -p "pls input two number:" a b c if [ -z $a ] then echo "you must input two number" exit elif [ -z $b ] then echo "you must input two number" exit fi if [ -z $c ] then expr $a + $b &>/dev/null if [ $? -eq 0 ] then echo "a-b=$(($a-$b))" echo "a+b=$(($a+$b))" echo "a*b=$(($a*$b))" echo "a/b=$(($a/$b))" else echo "input is not zhengshu" fi else echo "you must input two number" fi
執行結果如下,什麼都不輸入,輸入一個字符都會提示必須輸入2個數字;輸入2個值中有字母提示輸入的非整數;
[baby@localhost ~]$ sh a.sh pls input two number: you must input two number [baby@localhost ~]$ sh a.sh pls input two number:1 you must input two number [baby@localhost ~]$ sh a.sh pls input two number:1 a input is not zhengshu [baby@localhost ~]$ sh a.sh pls input two number:2 1 a-b=1 a+b=3 a*b=2 a/b=2
第二種方式:命令行腳本傳參方式 思路為:定義a b兩個變量,接受命令行傳遞的參數;$#為輸入參數的總個數;判斷輸入的參數個數不等於2,則提示必須輸入2個數字;等於2的話執行下面的腳本;
[baby@localhost ~]$ cat b.sh #!/bin/bash a=$1 b=$2 if [ $# -ne 2 ] then echo "you must input two number" exit 1 else expr $a + $b &>/dev/null if [ $? -eq 0 ] then echo "a-b=$(($a-$b))" echo "a+b=$(($a+$b))" echo "a*b=$(($a*$b))" echo "a/b=$(($a/$b))" else echo "input is not zhengshu" exit 1 fi fi
執行結果如下:傳參為空,參數為3個都會提示必須輸入2個數字;傳參包含非數字則提示輸入的不是整數;
[baby@localhost ~]$ sh b.sh 3 a input is not zhengshu [baby@localhost ~]$ sh b.sh 3 2 3 you must input two number [baby@localhost ~]$ sh b.sh 3 2 a-b=1 a+b=5 a*b=6 a/b=1
總結: read可以和用戶交互性較好,腳本較為復雜多了if判斷效率不高; 命令行傳參使用表達式判斷輸入參數,執行效率和理解性較好;