| Advanced Bash-Scripting Guide: A complete guide to shell scripting, using Bash | ||
|---|---|---|
| Prev | Chapter 3. Tutorial / Reference | Next |
3.13. Arithmetic Expansion
Arithmetic expansion provides a powerful tool for performing arithmetic operations in scripts. Translating a string into a numerical expression is relatively straightforward using backticks, double parentheses, or let.
- Arithmetic expansion with backticks (often used in conjunction with expr)
1 z=`expr $z + 3` # 'expr' does the expansion.
- Arithmetic expansion with double parentheses, and using let
The use of backticks in arithmetic expansion has been superseded by double parentheses $((...)) or the very convenient let construction.
All the above are equivalent. You may use whichever one "rings your chimes".1 z=$(($z+3)) 2 # $((EXPRESSION)) is arithmetic expansion. # Not to be confused with 3 # command substitution. 4 5 let z=z+3 6 let "z += 3" #If quotes, then spaces and special operators allowed. 7 # 'let' is actually arithmetic evaluation, rather than expansion.
Examples of arithmetic expansion in scripts:
