一、Bash 内置命令
1. declare / typeset 整数运算
-i The variable is treated as an integer; arithmetic evaluation (see ARITHMETIC EVALUATION above) is performed when the variable is assigned a value.
declare -i x=4+2
echo $x
6
declare -i x=4-2
echo $x
2
declare -i x=4*2
echo $x
8
declare -i x=4/2
echo $x
2
declare -i x=2**4
echo $x
16
typeset -i x=4+2
echo $x
6
typeset -i x=4-2
echo $x
2
typeset -i x=4*2
echo $x
8
typeset -i x=4/2
echo $x
2
typeset -i x=2**4
echo $x
16
2. let
let arg [arg ...]
Each arg is an arithmetic expression to be evaluated (see ARITH‐
METIC EVALUATION above). If the last arg evaluates to 0, let
returns 1; 0 is returned otherwise.
let x=4+2
echo $x
6
let x=4-2
echo $x
2
let x=4*2
echo $x
8
let x=4/2
echo $x
2
let x=4**2
echo $x
16
3. Arithmetic Expansion 算术展开
echo $((x=4+2))
6
echo $x
6
echo $((x=4-2))
2
echo $x
2
echo $((x=4*2))
8
echo $x
8
echo $((x=4/2))
2
echo $x
2
echo $((x=4**2))
16
echo $x
16
echo $[x=4+2]
6
echo $x
6
echo $[x=4-2]
2
echo $x
2
echo $[x=4*2]
8
echo $x
8
echo $[x=4/2]
2
echo $x
2
echo $[x=4**2]
16
echo $x
16
3. = 自然运算 SIMPLE COMMAND EXPANSION
x=4+2
echo $x
6
x=4-2
echo $x
2
x=4*2
echo $x
8
x=4/2
echo $x
2
x=2**4
echo $x
16
二、 expr
expr - evaluate expressions 计算表达式的值
expr 4 + 2
6
expr 4 - 2
2
expr 4 \* 2
8
expr 4 / 2
2
三、bc
bc - An arbitrary precision calculator language
echo "4+2" | bc
6
echo "4-2" | bc
2
echo "4*2" | bc
8
echo "4/2" | bc
2
echo "4^2" | bc
16
echo "sqrt(4)" | bc
2
echo "c(90)" | bc --mathlib
-.44807361612917015236
echo "s(90)" | bc --mathlib
.89399666360055789051
交互模式
bc --mathlib
bc 1.07.1
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
4+2
6
4-2
2
4*2
8
4/2
2.00000000000000000000
4^2
16
sqrt(4)
2.00000000000000000000
c(60)
-.95241298041515629269
c(30)
.15425144988758405071
c(45)
.52532198881772969604
c(90)
-.44807361612917015236
s(30)
-.98803162409286178998
[1] http://blog.csdn.net/taijianyu/article/details/6907288
[2] https://wiki.bash-hackers.org/syntax/ccmd/arithmetic_eval
[3] https://wiki.bash-hackers.org/syntax/arith_expr
[4] https://wiki.bash-hackers.org/syntax/expansion/arith
[5] man expr
[6] man let
[7] man bash
[8] man bc