Arithmetic Expansion

Advanced Bash-Scripting Guide: An in-depth exploration of the art of shell scripting
Prev |  | Next

# Chapter 13. Arithmetic Expansion

Arithmetic expansion provides a powerful tool for performing (integer) arithmetic operations in scripts. Translating a string into a numerical expression is relatively straightforward using backticks, double parentheses, or let.

Variations

Arithmetic expansion with backticks (often used in conjunction with expr)

         1 z=`expr $z + 3`          # The 'expr' command performs the expansion.

Arithmetic expansion with double parentheses, and using let

  The use of backticks (backquotes) in arithmetic expansion has been superseded by double parentheses -- `((...))` and `$((...))` -- and also by the very convenient let construction.

         1 z=$(($z+3))
         2 z=$((z+3))                                  #  Also correct.
         3                                             #  Within double parentheses,
         4                                             #+ parameter dereferencing
         5                                             #+ is optional.
         6
         7 # $((EXPRESSION)) is arithmetic expansion.  #  Not to be confused with
         8                                             #+ command substitution.
         9
        10
        11
        12 # You may also use operations within double parentheses without assignment.
        13
        14   n=0
        15   echo "n = $n"                             # n = 0
        16
        17   (( n += 1 ))                              # Increment.
        18 # (( $n += 1 )) is incorrect!
        19   echo "n = $n"                             # n = 1
        20
        21
        22 let z=z+3
        23 let "z += 3"  #  Quotes permit the use of spaces in variable assignment.
        24               #  The 'let' operator actually performs arithmetic evaluation,
        25               #+ rather than expansion.

  Examples of arithmetic expansion in scripts:

  1. Example 16-9

  2. Example 11-15

  3. Example 27-1

  4. Example 27-11

  5. Example A-16

Prev | Home | Next
Command Substitution | Up | Recess Time