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