歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> shell基礎:使用read、命令行腳本傳參實現輸入2個整數並計算

shell基礎:使用read、命令行腳本傳參實現輸入2個整數並計算

日期:2017/3/1 9:20:38   编辑:SHELL編程

shell基礎練習題:使用read交互輸入,命令行腳本傳參2種方式,實現輸入2個整數數字,並計算加減乘除。考察shell基礎知識包括:變量定義、read、if判斷語句、正則表達式等知識;

第一種方式:read交互輸入參數

思路為:判斷輸入的第2個變量是否為空,為空則提示輸入2個數字;不為空則判斷輸入的是否為整數,用到expr,作用為讓2個變量進行相加,如果結果為0說明輸入2個為數字,如結果非0則說明輸入非整數,提示輸入的不是非整數;

#!/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個參數也會報錯;

[linuxidc@localhost ~]$ sh a.sh
pls input two number:4 2
a-b=2
a+b=6
a*b=8
a/b=2
[linuxidc@localhost ~]$ sh a.sh
pls input two number:a 2
input is not zhengshu
[linuxidc@localhost ~]$ sh a.sh
pls input two number:10
you must input two number

腳本有bug,如果輸入3個參數的話會報錯如下:

[linuxidc@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個值中有字母提示輸入的非整數;

[linuxidc@localhost ~]$ sh a.sh
pls input two number:
you must input two number
[linuxidc@localhost ~]$ sh a.sh
pls input two number:1
you must input two number
[linuxidc@localhost ~]$ sh a.sh
pls input two number:1 a
input is not zhengshu
[linuxidc@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的話執行下面的腳本;

[linuxidc@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個數字;傳參包含非數字則提示輸入的不是整數;

[linuxidc@localhost ~]$ sh b.sh 3 a
input is not zhengshu
[linuxidc@localhost ~]$ sh b.sh 3 2 3
you must input two number
[linuxidc@localhost ~]$ sh b.sh 3 2
a-b=1
a+b=5
a*b=6
a/b=1

總結:

read可以和用戶交互性較好,腳本較為復雜多了if判斷效率不高;

命令行傳參使用表達式判斷輸入參數,執行效率和理解性較好;

Copyright © Linux教程網 All Rights Reserved