Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the self-defined function of Mathematical Operation with Shell

2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

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)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report