How to realize the self-defined function of Mathematical Operation with Shell
This article introduces the relevant knowledge of "how to use Shell to implement the custom function of mathematical operations". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Recently, there is always a need to calculate in the script, so it will be troublesome to use awk every time, so encapsulate the addition, subtraction, multiplication and division of awk, and call source math.sh directly each time.
There are some key points to point out so as not to forget when you revise them later:
1. Judge whether the two numbers are digits or not, and match them with awk
2. To do a cyclic check on the two parameters (it is clumsy to write two checks), you need to use the reference to the variable ${! Para} .
The code is as follows:
#! / bin/bash
# #
# rewrite basic mathematical operations in shell +-× /
# time: 2014-01-18
# email: jianye_jia@163.com
# version: version 1.0
# Note: currently, only 2-bit integer operations are supported
# #
#
# function is_Digit ()
# determine whether the parameter is numeric
# support floating point numbers
# only one parameter can be passed in
# Yes, return 1, otherwise return 0
# #
Functionis_Digit ()
{
Ref= `echo $1 | awk' {print ($0,00 / ^ [+ -]? [0-9]? * (\. [0-9] *)? $/)? "digit": "string"}'`
If ["$ref" = = "digit"]; then
Return0
Else
Return1
Fi
}
#
# function multiply ()
# determine whether the parameter is numeric
# and multiply the two parameters
# function passes in the reference directly
# implementation of variable ${! para}
The return value of # function, which cannot be return like C
# printout required, echo
#
Functionmul ()
{
For ((iTun1)