# Linux Shell Script Tutorial Series (v): mathematical operations

Source: Internet
Author: User

This article mainly introduces the Linux Shell Script series (v): Mathematical operations, this article explains the use of Let, (()) and [] arithmetic, using expr for arithmetic operations, using BC for arithmetic operations three ways, the need for friends can refer to the

Arithmetic operations are essential in any programming language, and the shell is no exception.

First, use Let, (()) and [] for arithmetic operations

You can use the normal variable assignment method to define a numeric value, which is that it will be saved as a string. We can use Let, (()), [] and other operators to make these variables to perform arithmetic operations. For example:

The code is as follows:

#!/bin/bash

No1=4 #此处no1义字符串形式存储

No2=5 #此处no2义字符串形式存储

Let Result=no1+no2

Echo \$result #输出结果为 9

Let-no1++ #等价于 let no1=no1+1

echo \$no 1 #输出结果为5

Let-no2--#等价于 let no2=no2-1

Echo \$no 2 #输出结果为 4

Let-no1+=5 #等价于 let no1=no1+5

echo \$no 1 #输出结果为10

Let-no1-=5 #等价于 let No1=no1-5

echo \$no 1 #输出结果为 5

No1=4 #此处no1义字符串形式存储

No2=5 #此处no2义字符串形式存储

result=\$[No1 + NO2]

echo \$result #输出结果为9

result=\$[\$no 1 + 5] #ubuntu中不能正常运行, No1 not found

echo \$result #输出结果为9

result=\$ ((no1 +)) #括号前的 \$ is not to be lost, otherwise the error

echo \$result #输出结果为 54

Third, using expr for arithmetic operations

The code is as follows:

Expr is a more advanced operator than the above three operators, and can alert advanced operations. For example:

#!/bin/bash

result= ' Expr 3 + 4 ' #此处用的不是单引号, but the TAB key above the symbol

echo \$result #输出结果为7

result= ' expr 3+4 ' #3与 + number per space

echo \$result #输出结果为 3+4

Note: The methods in 1.5.1 and 1.5.2 can only be evaluated for integers and cannot be counted in floating-point numbers.

Third, the use of BC for arithmetic operations

BC is an advanced tool for mathematical operations, which contains a large number of options that are usually placed before the specific operation to be performed, with semicolons as delimiters, passing a BC through Sdtin. For example:

echo "4 * 0.56" | BC #输出结果为2 24

The code is as follows:

no=54

Result= ' echo ' \$no * 1.5 | BC '

echo \$result #输出结果为81.0

echo "Scale=2;3/8" #通过scale舌质小数的精度, the output is 0.37

no=100

echo "Obase=2 \$no" | BC #进制转换, the target is binary, the default original system is 10

no=1100100

echo "Obase=10;ibase=2 \$no" | BC #obase =10,ibase=2

echo "sqrt (100)" | BC #计算平方根

echo "10^10" | BC #计算平方

-Note: Obase is the target, IBase is the original, by default the original system is 10.

Related Keywords:
Related Article

## E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

## Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

## Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD