Bash Bash Arithmetic Arithmetic command


Example

  • let
    let num=1+2
    let num="1+2"
    let 'num= 1 + 2'
    let num=1 num+=2 

You need quotes if there are spaces or globbing characters. So those will get error:

   let num = 1 + 2    #wrong
   let 'num = 1 + 2'  #right
   let a[1] = 1 + 1   #wrong
   let 'a[1] = 1 + 1' #right
  • (( ))
  ((a=$a+1))     #add 1 to a
  ((a = a + 1))  #like above
  ((a += 1))     #like above

We can use (()) in if. Some Example:

if (( a > 1 )); then echo "a is greater than 1"; fi 

The output of (()) can be assigned to a variable:

result=$((a + 1))

Or used directly in output:

echo "The result of a + 1 is $((a + 1))"