Use Shell to write a simple calculator, you can implement add, subtract, multiply, divide operation, if the script name is 1.sh, execute example:./1.sh 1 + 2
#!/bin/bashif [ $# -ne 3 ]then echo "The number of parameters should be 3, for example: $0 1 + 2 " echo " when using multiplication, you need to add the caret, for example: $0 1 \* 2 " exit 1;finum1= ' echo $1|sed ' s/[0-9. G ' if [ -n "$num 1" ]then echo "$ not number" exit 1finum3= ' echo $3|sed ' s/[0-9. G ' if [ -n "$num 3" ]then echo "$ $ not a number" exit 1ficase $2 in +) echo "Scale=2;$1+$3" | bc ;; -) echo "Scale=2;$1-$3" | bc ;; \*) echo "Scale=2;$1*$3" | bc ;; /) echo "Scale=2;$1/$3" | bc ;; *) echo "$2 not operator" ;; Esac
Analytical:
Number of $# parameters
The currently executing process name
Num1-ne num2 Not equal to [3-ne $mynum]
-N String if string length is nonzero, true [-n ' $myvar ']
Sed ' "n1,n2" "[0-9a-za-z]" s/source string/target string/g ' filename
Here n1,n2 refers to the interval N1 to N2 line, "s" is the command to replace, "G" for the bank in the global replacement, if not add ' g ', then only the first occurrence of the row. In addition to the use of "/" as a delimiter, you can also use other special words such as "#" or "@".
The BC command is a calculator language that supports interactive execution of arbitrary precision. Bash has built-in support for integer arithmetic, but it does not support floating-point operations, and the BC Command makes it easy to do floating-point arithmetic. The parameter scale=2 is set to 2 bits for the decimal digits of the BC output
Use case, if $ +, output echo "scale=2;$1+$3" | Bc
In turn on pushing
Output echo "$ not operator" If the subtraction is not in either case
Use Shell to write a simple calculator, you can implement add, subtract, multiply, divide operations, if the script name is 1.sh, execute example:./1.