This post is Part Two of Bash Programming. In this post, we will focus on doing arithmetics with Bash.
Operators
Basic
+
-
*
(Use\
to escape)/
(Result is integer, not float)%
expr
: Only among integers. e.g.
1 | expr 3 \* -2 / 5 |
Logic
!
(Not used in shell’s arithmetics)&
|
e.g.
1 | expr 1 \& 2 |
In commands:
1 && 2
1 || 2
(exec. 2 only if 1 fails)
Relational
=
>
<
<=
>=
Commands
expr
- No power or floats
(( ))
(是 [ ]
的进化版)
e.g.
echo $((2**3))
e.g.
1
2
3
4
5
6a=0
((a=a+3))
echo $a
>>> 3
let
: assignment & simple arithmetics
(( ))
‘s command version- e.g.
let 1+1
declare
: calculations use -i
1 | a=1+1 |
bc
: Linux calculator (ints & floats)
- e.g.
echo "1.1*3" | bc
Conditions
[[ ]]
equals to test
command
1 | test 3 -gt 2 -> [[ 3 > 2 ]] |
File type:
-d
: Is it a dir.-e
: Does it contain this file-r
: Is it read-only- e.g.
1
2
3
4
5[ -d /home/test ]
echo $?
[[ -r /home/test && -e /test/hello ]]
echo $?
Special
Convert decimal to binary:
1 | echo "obase=2; ibase=10; 11" | bc -l |
Convert binary to decimal:
1 | echo $(( 2#1011 )) |
Get random numbers (Default: 0 - 32767):
1 | echo $RANDOM |
Get random numbers (0 - 255):
1 | expr $RANDOM / 128 |
More flexible way:
1 | shuf -i 100-300 -n 4 |
- Range (
-i
) - # of outputs (
-n
)