close

#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:~/bin
export PATH

add="add"
sub="sub"
mul="mul"
div="div"

while true
do
        j=0
        answer=0
        echo "=========="
        echo "請以add 取代+"
        echo "請以sub 取代-"
        echo "請以mul 取代*"
        echo "請以div 取代/"
        echo "=========="
        read -p "Please Input number(ex.add 1 2 3):" A[0]
        for i in ${A[0]}
        do
                if [ $j == 0 ]; then
                        option=$i
                        j=$(($j+1))
                else
                        tmp[$j]=$i
                        j=$(($j+1))
                fi
        done

        case $option in
                $add)
                        answer=0
                       for ((k=1; k<$j; k++))
                        do
                                answer=$(($answer+$((tmp[$k]))))
                        done
                        ;;
                $sub)
                        answer=${tmp[1]}
                        for ((k=2; k<$j; k++))
                        do
                                answer=$(($answer-$((tmp[$k]))))
                        done
                        ;;
                $mul)
                        answer=${tmp[1]}
                        for ((k=2; k<$j; k++))
                        do
                                answer=$(($answer*$((tmp[$k]))))
                        done
                        ;;
                $div)
                        answer=${tmp[1]}
                        for ((k=2; k<$j; k++))
                        do
                                answer=$((($answer)/$((tmp[$k]))))
                        done
                        ;;
                *)
                        echo "Please input add, sub, mul or div, thanks."
                        continue
                        ;;
        esac

        echo "The answer is $answer"
done

exit 0

執行結果如下:

[root@walter testshell]# ./test2
==========
請以add 取代+
請以sub 取代-
請以mul 取代*
請以div 取代/
==========
Please Input number(ex.add 1 2 3):add 2 3 4
The answer is 9
==========
請以add 取代+
請以sub 取代-
請以mul 取代*
請以div 取代/
==========
Please Input number(ex.add 1 2 3):sub 4 2 1
The answer is 1
==========
請以add 取代+
請以sub 取代-
請以mul 取代*
請以div 取代/
==========
Please Input number(ex.add 1 2 3):mul 2 3 4
The answer is 24
==========
請以add 取代+
請以sub 取代-
請以mul 取代*
請以div 取代/
==========
Please Input number(ex.add 1 2 3):div 9 3 3
The answer is 1

arrow
arrow
    全站熱搜

    Walter Blyss 發表在 痞客邦 留言(1) 人氣()