Shell script topic-mathematical operations (3)

In the shell environment, you can use let, (()), [] to perform basic arithmetic calculations. When performing advanced operations, expr and bc are also often used.
Just look at the example:

#!/bin/bash

# shell中变量默认都是字符串,我们可以使用一些方法让它能像数字一样进行运算
number1=10;
number2=20;

# 1.let命令可以直接进行算数操作,当使用let命令的时候,变量名前面不需要加上$
let result=number1+number2;
echo "number1+number2 = $result"

# 自加和自减操作
let result--
let result++
echo "result自加和自减操作以后的数值: $result"

# 2.操作符[]的使用方法和let相似
result2=$[number1+number2]
echo "[]操作演示: $result2"

# 3.(()) 的使用, 变量名之前需要加上$
result3=$(($number1 + 10))
echo "(()) 操作演示: $result3"

# 4.expr操作也可以对整数进行操作,不支持浮点数的计算
expr1=`expr 3 + 10`   # 注意操作符前后都有空格
echo "expr 演示, `expr 3+10` : $expr1"

# 5.bc是一个用于数学计算的高级工具,可以使用他执行浮点数的计算
echo "4 *10.251" | bc

# 6.bc操作进行进制转换
no=100
echo "100转换为二进制为: "
echo "obase=2;$no" | bc

# 二进制转换为10进制
echo "obase=10;ibase=2;$no" | bc

#计算平方及其平方根
echo -n "1000的平方根: "
echo "sqrt(1000)" | bc
echo -n "10的10次方为: "
echo "10 ^ 10" | bc

The output is as follows:

number1+number2 = 30
result自加和自减操作以后的数值: 30
[]操作演示: 30
(()) 操作演示: 20
expr 演示, 3+10 : 13
41.004
100转换为二进制为: 
1100100
4
1000的平方根: 31
10的10次方为: 10000000000


Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
![Insert picture description here](https://img-blog.csdnimg.cn/20201022235707220.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_#!/bin/bash

By default, variables in the shell are strings. We can use some methods to make them operate like numbers.

number1=10;
number2=20;

1. The let command can directly perform arithmetic operations. When using the let command, the variable name does not need to be prefixed with $

let result=number1+number2;
echo “number1+number2 = $result”

Add and subtract operations

let result–
let result++
echo “result value after addition and subtraction operations: $result”

2. The use of operator [] is similar to let

result2=$[number1+number2]
echo "[] Operation demonstration: $result2"

3. For the use of (()), you need to add $ before the variable name

result3= ( ( (( ( ( number1 + 10))
echo "(()) operation demonstration: $result3"

4. The expr operation can also operate on integers, and does not support the calculation of floating point numbers

expr1= expr 3 + 10# Note that there are spaces before and after the operator echo "expr demo expr 3+10,: $expr1"

5.bc is an advanced tool for mathematical calculations, you can use it to perform floating point calculations

echo “4 *10.251” | bc
10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2hvbmdnZV9zbWlsZQ==,size_16,color_FFFFFF,t_70#pic_center)
Insert picture description here

Guess you like

Origin blog.csdn.net/hongge_smile/article/details/109233410