bash aritmethic - ghdrako/doc_snipets GitHub Wiki

The shell allows arithmetic expressions to be evaluated, as one of the

  • shell expansions or
  • by using the (( compound command,
  • the let builtin, or
  • the -i option to the declare builtin.

Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is:

$(( expression ))
#add integers a to b and assign to c:
a=5
b=7
c=$((a+b))

Aritmetics

$ a=5; a+=2; echo "$a"; unset a
52
$ a=5; let a+=2; echo "$a"; unset a
7
$ declare -i a=5; a+=2; echo "$a"; unset a
7
$ a=5+2; echo "$a"; unset a
5+2
$ declare -i a=5+2; echo "$a"; unset a
7

Most experienced shell scripters prefer to use explicit arithmetic commands (with ((...)) or let) when they want to perform arithmetic. And they don't use declare -i. The same is explicit declaration of an array using declare -a. It is sufficient to write array=(...) insteed. The exception to this is the associative array, which must be declared explicitly: declare -A myarray.

declare -i MYVAR #declare variable as integer
declare -i SEE
X=9
Y=3
SEE=X+Y            # only this one will be arithmetic
SAW=X+Y            # this is just a literal string
SUM=$X+$Y          # this is string concatenation
echo "SEE = $SEE"
echo "SAW = $SAW"
echo "SUM = $SUM"
step=$(( step + 1 )) # $((step++)) will return a numeric value — Which the shell will then take as the name of a command to be executed. If step++ evaluated to 3 then the shell would look for a command named 3.
median_loc=$(( len / 2 ))
dist=$(( dist * 4 ))
if (( OTHERVAL * 10 <= VAL / 5 )) ; then ...

EXPR

Basic arithmetic using expr

expr 5 + 4
expr "5 + 4"
expr 5+4
expr 5 \* $1
expr 11 % 2
a=$( expr 10 - 3 )
echo $a # 7

BC

echo "12+5" | bc
echo "10^2" | bc
x=`echo "12+5" | bc`
echo $x
#Output:17

pi=`echo "h=10;4*a(1)" | bc -l`
echo $pi

echo "e(3)" | bc -l #exponential^value as output
echo "ibase=2;1111" | bc -l # Convert Decimal to Octal
echo "ibase=2;1111" | bc -l # Convert Binary to Decimal
echo "ibase=2;obase=8;10" | bc -l # Convert Binary to Octal