Advanced Bash-Scripting Guide: An in-depth exploration of the art of shell scripting | ||
---|---|---|
Prev | Chapter 8. Operations and Related Topics | Next |
Similar to the let command, the (( ... )) construct permits arithmetic expansion and evaluation. In its simplest form, a=$(( 5 + 3 )) would set a to 5 + 3, or 8. However, this double-parentheses construct is also a mechanism for allowing C-style manipulation of variables in Bash, for example, (( var++ )).
Example 8-5. C-style manipulation of variables
1 #!/bin/bash 2 # c-vars.sh 3 # Manipulating a variable, C-style, using the (( ... )) construct. 4 5 6 echo 7 8 (( a = 23 )) # Setting a value, C-style, 9 #+ with spaces on both sides of the "=". 10 echo "a (initial value) = $a" # 23 11 12 (( a++ )) # Post-increment 'a', C-style. 13 echo "a (after a++) = $a" # 24 14 15 (( a-- )) # Post-decrement 'a', C-style. 16 echo "a (after a--) = $a" # 23 17 18 19 (( ++a )) # Pre-increment 'a', C-style. 20 echo "a (after ++a) = $a" # 24 21 22 (( --a )) # Pre-decrement 'a', C-style. 23 echo "a (after --a) = $a" # 23 24 25 echo 26 27 ######################################################## 28 # Note that, as in C, pre- and post-decrement operators 29 #+ have different side-effects. 30 31 n=1; let --n && echo "True" || echo "False" # False 32 n=1; let n-- && echo "True" || echo "False" # True 33 34 # Thanks, Jeroen Domburg. 35 ######################################################## 36 37 echo 38 39 (( t = a<45?7:11 )) # C-style trinary operator. 40 # ^ ^ ^ 41 echo "If a < 45, then t = 7, else t = 11." # a = 23 42 echo "t = $t " # t = 7 43 44 echo 45 46 47 # ----------------- 48 # Easter Egg alert! 49 # ----------------- 50 # Chet Ramey seems to have snuck a bunch of undocumented C-style 51 #+ constructs into Bash (actually adapted from ksh, pretty much). 52 # In the Bash docs, Ramey calls (( ... )) shell arithmetic, 53 #+ but it goes far beyond that. 54 # Sorry, Chet, the secret is out. 55 56 # See also "for" and "while" loops using the (( ... )) construct. 57 58 # These work only with version 2.04 or later of Bash. 59 60 exit |
See also Example 11-13 and Example 8-4.