Arithmetic Expansion

Chapter 12. 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)

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.

z=$(($z+3))
z=$((z+3))                                  #  Also correct.
                                            #  Within double parentheses,
                                            #+ parameter dereferencing
                                            #+ is optional.

# $((EXPRESSION)) is arithmetic expansion.  #  Not to be confused with
                                            #+ command substitution.



# You may also use operations within double parentheses without assignment.

  n=0
  echo "n = $n"                             # n = 0

  (( n += 1 ))                              # Increment.
# (( $n += 1 )) is incorrect!
  echo "n = $n"                             # n = 1


let z=z+3
let "z += 3"  #  Quotes permit the use of spaces in variable assignment.
              #  The 'let' operator actually performs arithmetic evaluation,
              #+ rather than expansion.

Examples of arithmetic expansion in scripts:

  1. Example 15-9

  2. Example 10-14

  3. Example 26-1

  4. Example 26-11

  5. Example A-16


199 visits (2 today, 10 this week, 28 this month, 199 this year)
Uptime: 17:45:22 up 3 days, 23:28, 3 users, load average: 0.00, 0.00, 0.00
18.227.21.101 GET from server z.larrymurakami.com

Saturday, December 21, 2024 @ 5:45:22 PM
z.ServerAdmin@lam1.us