0%

Linux基础--算数运算

算术运算

(1)bash 中的算术运算:

help let +, -, *, /, % 取模(取余), ** (乘方)

(2)实现算术运算:

  • (1) let var= 算术表达式
  • (2) var=$[ 算术表达式]
  • (3) var=$(( 算术表达式))
  • (4) var=$(expr arg1 arg2 arg3 …)
  • (5) declare –i var = 数值
  • (6) echo ‘ 算术表达式’ | bc
  • (7) 乘法符号有的场景需要转义*
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@localhost ~]# num1=1
[root@localhost ~]# num2=2
[root@localhost ~]# let sum=${num1}+${num2} && echo $sum
3
[root@localhost ~]# echo $[${num1}+${num2}]
3
[root@localhost ~]# echo $((${num1}+${num2}))
3
[root@localhost ~]# mult=$(expr ${num1} \* ${num2})
[root@localhost ~]# echo $mult
2
[root@localhost ~]# declare -i var=${num1}+${num2} && echo $sum
3
[root@localhost ~]# echo "${num1}+${num2}" | bc
3

(3)增强型赋值:+=, -=, *=, /=, %=

let var OPER value

例如:

1
2
3
4
5
6
7
8
9
10
11
自增,自减:
let var+=1
let var++
let var--
[root@localhost ~]# var=0
[root@localhost ~]# let var+=1 && echo $var
1
[root@localhost ~]# let var++ && echo $var
2
[root@localhost ~]# let var-- && echo $var
1