Numerical operation shell script

Time:2021-6-13

This shell case is relatively simple, but it has its own characteristics.


#!/bin/sh

# scriptbc - Wrapper for 'bc' that returns the result of a calculation.

if [ $1 = "-p" ] ; then
 precision=$2
 shift 2
else
 precision=2      # default
fi

bc -q << EOF
scale=$precision
$*
quit
EOF

exit 0

Script features:
1) The script as a whole is concise and clear, but it is powerful, and can realize the operation with custom value.
2) Scale = $precision is a parameter passed to BC to display the number of decimal places
3)<< EOF
scale=$precision $* quit
EOF
It is used to pass values to the script, similar to the effect of manual input in bash.
4) precision=$2 ; Shift 2 is an interesting line. With this, you can implement the function of script parameters,
Shift 2 means to shift the input parameter to the left by 2 bits, i.e. $1, clear $2 first, assign $3 to $1 and $4 to $2.