Merikanto

一簫一劍平生意,負盡狂名十五年

Bash Programming - 02 Arithmetics

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
2
expr 3 \* -2 / 5
>>> -1

Logic

  • ! (Not used in shell’s arithmetics)
  • &
  • |

e.g.

1
2
3
4
5
6
7
8
expr 1 \& 2
>>> 1

expr 2 \& 0
>>> 0

expr 2 \| 0
>>> 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
    6
    a=0
    ((a=a+3))
    echo $a

    >>> 3


let: assignment & simple arithmetics

  • (( ))‘s command version
  • e.g. let 1+1


declare: calculations use -i

1
2
3
4
5
a=1+1
declare -i a
echo $a

>>> 2

bc: Linux calculator (ints & floats)

  • e.g. echo "1.1*3" | bc

Conditions

[[ ]] equals to test command

1
2
3
4
test 3 -gt 2  	->   [[ 3 > 2 ]]
echo $?

>>> 0 # True

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
2
3
echo "obase=2; ibase=10; 11" | bc -l

>>> 1011

Convert binary to decimal:

1
2
3
echo $(( 2#1011 ))	

>>> 11

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)