Shell 实现简单计算器功能,脚本如下:
[[email protected] scripts]# cat jisuan.sh #!/bin/bash print_usage(){ printf $"USAGE:$0 NUM1 {+|-|*|/} NUM2\n" exit 1 } #判断传入的参数是不是3个 if [ $# -ne 3 ] then print_usage fi firstnum=$1 secondnum=$3 op=$2 #对传入的参数进行判断看是不是合理 if [ -n "`echo $firstnum|sed ‘s/[0-9]//g‘`" ];then print_usage fi if [ "$op" != "+" ]&&[ "$op" != "-" ]&&[ "$op" != "*" ]&&[ "$op" != "/" ];then print_usage fi if [ -n "`echo $secondnum|sed ‘s/[0-9]//g‘`" ];then print_usage fi echo "${firstnum}${op}${secondnum}=$((${firstnum}${op}${secondnum}))"
调试:
[[email protected] scripts]# sh -x jisuan.sh 6 + 4 + ‘[‘ 3 -ne 3 ‘]‘ + firstnum=6 + secondnum=4 + op=+ ++ sed ‘s/[0-9]//g‘ ++ echo 6 + ‘[‘ -n ‘‘ ‘]‘ + ‘[‘ + ‘!=‘ + ‘]‘ ++ sed ‘s/[0-9]//g‘ ++ echo 4 + ‘[‘ -n ‘‘ ‘]‘ + echo 6+4=10 6+4=10 [[email protected] scripts]# sh -x jisuan.sh 5 \* 5 + ‘[‘ 3 -ne 3 ‘]‘ + firstnum=5 + secondnum=5 + op=‘*‘ ++ sed ‘s/[0-9]//g‘ ++ echo 5 + ‘[‘ -n ‘‘ ‘]‘ + ‘[‘ ‘*‘ ‘!=‘ + ‘]‘ + ‘[‘ ‘*‘ ‘!=‘ - ‘]‘ + ‘[‘ ‘*‘ ‘!=‘ ‘*‘ ‘]‘ ++ sed ‘s/[0-9]//g‘ ++ echo 5 + ‘[‘ -n ‘‘ ‘]‘ + echo ‘5*5=25‘ 5*5=25
注意:
- “-x”表示调试,可以看见执行的步骤
- 对应 “*” 需要加 “\”转义
时间: 2024-12-26 16:19:47