29.shell腳本正整數加減乘除計算

思路:函數先計算數值加減乘除,case賦值輸出對應的加減乘除
#!/bin/bash
add() { 
        add=$[$1+$2]
        echo "outcome:$1+$2=$add"
}
minus() {
        min=$[$1-$2]
        echo "outcome:$1-$2=$min"
}
multiply() {
        mult=$[$1*$2]
        echo "outcome:$1x$2=$mult"
}
divide() {
        div=$[$1/$2]
        echo "outcome:$1/$2=$div"
}
positive_integer() {
        if echo $1| grep -q [^0-9];then
        echo "please input a positive number."
        exit 2
        fi

}
if [ $# -ne 3 ];then  #判斷輸入參數爲3
#第二個參數不能爲*,shell腳本中*表明是特殊字符,所以乘應使用x代替
        echo "please input three parameter,format like: number1 (+ - x /) number2"
        exit 1
else
        positive_integer $1#調用函數判斷正整數
        positive_integer $3#調用函數判斷正整數

fi

case $2 in
        x)
        multiply $1 $3
        ;;
        +)
        add $1 $3
        ;;
        -)
        minus $1 $3
        ;;
        /)
        if [ $1 -lt $3 ];then
        echo "input first number $1 must great second number $3,else outcome number is zero."
else
        divide $1 $3
        fi
        ;;
        \*)
        echo "please input three parameter,format like: number1 (+ - x /) number2"
        ;;
esac
用法 : sh  jjcc.sh 3 x 4 
輸出:outcome:3 x 4=12
注:除法若是想保留兩位小數可使用 echo "scale=2;1/2"| bc實現
相關文章
相關標籤/搜索