The arithmetic Detailed shell scripts

Arithmetic operators as follows:

The arithmetic Detailed shell scripts

Operator that operational command:

The arithmetic Detailed shell scripts

1, double parentheses "(())" command value calculation

Dual role parentheses "(())" is the numerical value of the comparison operation, it is the most efficient, flexible usage, is often employed arithmetic operator, which operation is as follows:

The arithmetic Detailed shell scripts

When executed echo $ ((a ++)) and echo $ ((a--)) command entire output expression, the output value is the value of a, the expression is finished, will be a ++, - the operations, and execute echo $ ((++ a)) and echo $ ((- a)) command to output the entire expression will be a first for ++, - the operation, then the output value of the expression , that is, a value obtained by calculation.

Note: For ++, - memory method of operation:

  • Before a variable operator, the output expression is a, then a decrement or increment; after a variable operator, the output from the first expression will be incremented and decremented, the value of the expression is the increment or subtracted the value of a.
  • "(())" When the expression does not require additional command line $ symbols used directly ((6% 2)) forms can, if desired output, will add $ symbol, e.g.: echo $ ((6 %2)).
  • "(())" There is no space between the characters in all, there are one or more spaces will not affect the results.

Example of use:

[root@localhost ~]# echo $(( 6+2 ))    #加法
8
[root@localhost ~]# echo $(( 6-2 ))    #减法
4
[root@localhost ~]# echo $(( 6*2 ))    #乘法
12
[root@localhost ~]# echo $(( 6/2 ))    #除法
3
[root@localhost ~]# echo $(( 6%2 ))    #取余
0
[root@localhost ~]# echo $(( 6**2 ))    #求平方
36
[root@localhost ~]# a=3     #给变量赋值
[root@localhost ~]# echo $(( a++ ))    #先输出变量值,再+1
3
[root@localhost ~]# echo ${a}     #再查看变量,发现+1了
4
[root@localhost ~]# echo $(( a-- ))   #先输出变量值,再-1
4
[root@localhost ~]# echo ${a}    #再查看变量,发现-1了
3
[root@localhost ~]# echo $(( ++a ))    #先+1,再输出变量值,输出的是+1后的值
4
[root@localhost ~]# echo ${a}     #确认变量值
4
[root@localhost ~]# echo $(( --a ))     #先-1,再输出变量值
3
[root@localhost ~]# echo ${a}      #查看确认
3

2, let operation command usage

let assignment expression is functionally equivalent to "((assignment expression))"

Example of use:

[root@localhost ~]# i=1
[root@localhost ~]# echo $i
1
[root@localhost ~]# let i=i+8     #加8
[root@localhost ~]# echo $i      #输出
9
[root@localhost ~]# let i=i-1     #i-1
[root@localhost ~]# echo $i     #输出
8
[root@localhost ~]# let i++     #我在shell  script中常使用这种方法,默认+1
[root@localhost ~]# echo $i
9
[root@localhost ~]# let i--       #i-1
[root@localhost ~]# echo $i
8

3, use the command expr

effect:

expr (evaluate (evaluation) Expressions (expression)) may be used for integer arithmetic command it may be used for the relevant length of the string matching operation processing.

(1) expr for calculating:

[root@localhost ~]# expr 2 + 3
5
[root@localhost ~]# expr 2 \* 3     #*号需要转义后使用
6
[root@localhost ~]# expr 6 / 3
2
[root@localhost ~]# expr 7 % 3
1

When using expr Note:

  • Operators for calculating the left and right digital and have at least one space, to avoid an error.
  • When using a multiplication sign, it must be escaped with a backslash (converted to ordinary characters), because Shell might misunderstand the meaning of an asterisk.

(2) expr complex variable calculation

[root@localhost ~]# i=5
[root@localhost ~]# i=`expr ${i} + 5`      #需要使用反撇号将其括起来,注意变量和数字符号两边要有空格
[root@localhost ~]# echo ${i}
10

(3) determining whether a variable is an integer or string

The principle is to use the time to do the calculation variables expr or string must be regular integer, or string to a variable integer and a known (non-zero) are added, to see whether the command returns the value 0. If 0, do you think the addition of a variable is an integer or string, otherwise it is not an integer.

Example 1:

[root@localhost ~]# a=2        
[root@localhost ~]# expr ${a} + 5
7
[root@localhost ~]# echo $?       #输出为0,说明变量a是一个整数
0
[root@localhost ~]# b=lvjianzhao    #定义一个字符变量
[root@localhost ~]# expr ${b} + 5    #实际上会直接报错
expr: 非整数参数
[root@localhost ~]# echo $?       #输出为非0,则表示变量b不是一个整数
2

Example 2:

[root@localhost ~]# vim test.sh 

#!/bin/bash
expr $1 + 4 &> /dev/null
if [ $? -eq 0 ]
        then
          echo int
        else
          echo chars
fi
[root@localhost ~]# sh test.sh aaa    
chars                   #输出的结果是字符串
[root@localhost ~]# sh test.sh 34
int               #输出的结果是整数型

Example 3:

#!/bin/bash
tuichu(){
        exit 0
}
while true
do
        read -p "pls input:" a
        expr $a + 0 > /dev/null 2>&1
        [ $? -eq 0 ] && echo int || echo chars
        if [ $a == exit ]
          then
                tuichu              #调用开头定义的函数
        fi
done
[root@localhost ~]# sh test.sh     #执行脚本
pls input:22             #输入数字进行测试
int
pls input:dfdf           #输入字符进行测试
chars
pls input:exit            #输入exit,将触发函数,而退出脚本,若不定义这个函数,只能通过ctrl+c强制中断脚本执行
chars
[root@localhost ~]#

4, bc computer usage

(1) In the direct input mode command BC, can be used directly after the press Enter, as follows:

[root@localhost ~]# bc      #输入bc进入计算机环境
bc 1.06.95
                                 ........................#省略部分内容
1+8         #输入后按回车即可得到结果
9
9/3
3
6*2
12

(2) The following command line bc used to implement arithmetic functions:

[root@localhost ~]# echo 3+4 | bc       #通过echo命令结合管道符输出到bc计算机
7
[root@localhost ~]# echo "3.4+5.6" | bc
9.0
[root@localhost ~]# echo "3.2-2.5" | bc
.7
[root@localhost ~]# echo "scale=2;355/113" | bc   #使用scale参数可以设置保留的小数位
3.14
[root@localhost ~]# echo "scale=6;355/113" | bc
3.141592

(3) using the complex variable calculation bc:

[root@localhost ~]# i=5
[root@localhost ~]# i=`echo $i+6|bc`    利用echo输出,通过管道符交给bc,此方法效率较低,一般不使用。
[root@localhost ~]# echo $i
11

Tip: The bc has the particularity of view, if a decimal, the select operation is no problem bc (more recommended awk); if integer scene, can be used "(())", let , expr like.

(4) using the output of a command calculating the expression 1 + 2 + 3 .... + 10, and calculates the result (using computer implemented bc)

Generating .... 1 + 2 + 3 + 10 expression methods are:

[root@localhost ~]# seq -s "+" 10           #seq是生成数字序列,-s是指定数字序列之间的分隔符
1+2+3+4+5+6+7+8+9+10
[root@localhost ~]# echo {1..10} | tr " " "+"   #生成以空格为间隔的数字序列,并交给tr将空格替换为+号
1+2+3+4+5+6+7+8+9+10

Various methods to achieve the above requirement as follows:

#使用bc计算
[root@localhost ~]# echo `seq -s "+" 10`=`seq -s "+" 10 | bc`
1+2+3+4+5+6+7+8+9+10=55
#使用(())计算
[root@localhost ~]# echo `seq -s "+" 10`=$((`seq -s "+" 10`))
1+2+3+4+5+6+7+8+9+10=55
#使用expr计算
[root@localhost ~]# echo `seq -s '+' 10`=`seq -s " + " 10|xargs expr`
1+2+3+4+5+6+7+8+9+10=55
使用$[ ] 来计算
[root@localhost ~]# echo `seq -s '+' 10`=$(echo $[ `seq -s '+' 10` ])
1+2+3+4+5+6+7+8+9+10=55

5, awk realized computing function

Using awk calculates the effect is also very good for the fractional and integral, in particular command line calculation, in particular fractional arithmetic very accurate, easy to use.

Example of use:

[root@localhost ~]# echo "7.7 8.5" |awk '{print ($1-$2)}'
-0.8
[root@localhost ~]# echo "7.7 3.5" |awk '{print ($1-$2)}'
4.2
[root@localhost ~]# echo "358 114" | awk '{print ($1-2)/$2}'
3.12281
[root@localhost ~]# echo "3 8" | awk '{print ($1+3)*$2}'
48

6, declare (with typeset) command usage

Require the use of typeset define integer variables, direct calculation, this method is not used, because you need to define take effect.

Use examples:

[root@localhost ~]# declare -i A=20 B=3    #-i参数可以将变量定义为整型
[root@localhost ~]# A=A+B    #因为已声明是整型,因此可以直接进行运算了。
[root@localhost ~]# echo $A     #输出查看
23

7, $ [] operation symbol

The basic format is as follows (as for operators, and the other tools of the same operation):

[root@localhost ~]# i=4
[root@localhost ~]# i=$[i+3]
[root@localhost ~]# echo ${i}
7
[root@localhost ~]# echo $[2*3]
6
[root@localhost ~]# echo $[9/3]
3
[root@localhost ~]# echo $[10%3]
1
[root@localhost ~]# echo $[1%3]
1
[root@localhost ~]# echo $[3/2]
1

-------- end of this article so far, thanks for reading --------

Guess you like

Origin blog.51cto.com/14154700/2434448