The Shell implements a simple calculator function with the following script:
[[email protected] scripts]# Cat Jisuan.sh#!/bin/bashprint_usage () {printf $ "usage:$0 NUM1 {+|-|*|/} num2\n" Exit 1} #判断传入的参数是不是3个if [$#-ne 3] then print_usagefifirstnum=$1secondnum=$3op=$2# to determine the incoming parameters to see if it is reasonable if [-n "' Echo $firstnum |s Ed ' s/[0-9]//g ' "];then print_usagefiif [" $op "! =" + "]&&[" $op "! ="-"]&&[" $op "! =" * "]&& ["$op"! = "/"];then Print_usagefiif [-N "' Echo $secondnum |sed ' s/[0-9]//g '"];then Print_usagefiecho "${firstnum} ${op}${secondnum}=$ ((${firstnum}${op}${secondnum})) "
Debugging:
[[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=106+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 ' /[0-9]//g ' ++ echo 5+ ' [' -n ' '] ' + echo ' 5*5=25 ' 5*5=25
Attention:
"-X" means debugging, and you can see the steps performed
The corresponding "*" needs to be escaped with "\"
This article is from the "Knowledge Change Destiny" blog, please be sure to keep this source http://ahtornado.blog.51cto.com/4826737/1927919
Shell Implements simple calculator function