前一段时间受人之托,说是毕业设计非要用shell写个计算器,要支持四则运算的,刚开始觉得还容易,可发现四则的匹配还是比较繁琐的,在这里分享下吧~估计之后也不会出这样的毕业设计了
PS:赶时间写的,有bug的欢迎指正
- #!/bin/bash
- ## Calculator.sh ##
- main()
- {
- echo 'This is a Calculator:'
- echo 'example: 3 + 90 x ( 9 - 5 ) / 3 - 23'
- call
- }
- call()
- {
- while [ 1 ];do
- read str
- u=($str)
- g1='no'
- g2='no'
- nu=`echo $str | awk '{print NF}'`
- for((i=0;i<$nu;i++));do
- echo ${u[$i]} | grep -E '^[1-9]|+|-|x|/|\(|\)' > /dev/null
- if (( $? == 0 ));then
- echo ${u[$i]} |grep -E '\(|\)' > /dev/null
- if (( $? == 0 ));then
- echo ${u[$i]} |grep -w '(' > /dev/null
- if (( $? == 0 ));then
- g1=$i
- continue
- fi
- echo ${u[$i]} |grep -w ')' > /dev/null
- if (( $? == 0 ));then
- g2=$i
- if [ $g1 != 'no' ] || [ $g2 != 'no' ];then
- compute $g1 $g2
- u[$g1]=$?
- for((p=$g1+1;p<$g2+1;p++));do
- u[$p]=''
- done
- # echo ${u[@]}
- nu3=`echo ${u[@]} | awk '{print NF}'`
- compute 0 $nu3
- echo $?
- fi
- continue
- fi
- fi
- else
- echo 'Error: is not digital'
- fi
- done
- if [ $g1 = 'no' ] || [ $g2 = 'no' ];then
- compute 0 $nu
- echo $?
- fi
- done
- }
- compute()
- {
- s=(${u[@]})
- for((k=$1;k<$2;k++));do
- echo ${s[$k]} |grep -E 'x|/' > /dev/null
- if (( $? == 0 ));then
- echo ${s[$k]} |grep -w 'x' > /dev/null
- if (( $? == 0 ));then
- sum=`expr ${s[$k-1]} \* ${s[$k+1]}`
- s[$k+1]=$sum
- s[$k]=''
- s[$k-1]=''
- continue
- fi
- echo ${s[$k]} |grep -w '/' > /dev/null
- if (( $? == 0 ));then
- sum=`expr ${s[$k-1]} \/ ${s[$k+1]}`
- s[$k+1]=$sum
- s[$k]=''
- s[$k-1]=''
- continue
- fi
- fi
- echo ${s[@]} |grep -E '+|-' > /dev/null
- if (( $? == 0 ));then
- t=(${s[@]})
- nu2=`echo ${t[@]} | awk '{print NF}'`
- for((j=$1;j<$2;j++));do
- echo ${t[$j]} |grep -E '+|-' > /dev/null
- if (( $? == 0 ));then
- echo ${t[$j]} |grep -w '+' > /dev/null
- if (( $? == 0 ));then
- sum=`expr ${t[$j-1]} + ${t[$j+1]}`
- t[$j+1]=$sum
- t[$j]=''
- t[$j-1]=''
- continue
- fi
- echo ${t[$j]} |grep -w '-' > /dev/null
- if (( $? == 0 ));then
- sum=`expr ${t[$j-1]} - ${t[$j+1]}`
- t[$j+1]=$sum
- t[$j]=''
- t[$j-1]=''
- continue
- fi
- fi
- done
- fi
- done
- return $sum
- }
运行结果:
- zhangbo@ufo:~/me/shell$ ./Calculator.sh
- This is a Calculator:
- example: 3 + 90 x ( 9 - 5 ) / 3 - 23
- 3 + 90 x ( 9 - 5 ) / 3 - 23
- 100
- 2 x ( 3 + 10 )
- 26