9.7. The Double Parentheses Construct

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-type manipulation of variables in Bash.


Example 9-29. C-type 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, with spaces on both sides of the "=".
   8 echo "a (initial value) = $a"
   9 
  10 (( a++ ))     # Post-increment 'a', C-style.
  11 echo "a (after a++) = $a"
  12 
  13 (( a-- ))     # Post-decrement 'a', C-style.
  14 echo "a (after a--) = $a"
  15 
  16 
  17 (( ++a ))     # Pre-increment 'a', C-style.
  18 echo "a (after ++a) = $a"
  19 
  20 (( --a ))     # Pre-decrement 'a', C-style.
  21 echo "a (after --a) = $a"
  22 
  23 echo
  24 
  25 (( t = a<45?7:11 ))   # C-style trinary operator.
  26 echo "If a < 45, then t = 7, else t = 11."
  27 echo "t = $t "        # Yes!
  28 
  29 echo
  30 
  31 
  32 # -----------------
  33 # Easter Egg alert!
  34 # -----------------
  35 #  Chet Ramey apparently snuck a bunch of undocumented C-style constructs
  36 #+ into Bash (actually adapted from ksh, pretty much).
  37 #  In the Bash docs, Ramey calls ((...)) shell arithmetic,
  38 #+ but it goes far beyond that.
  39 #  Sorry, Chet, the secret is now out.
  40 
  41 # See also "for" and "while" loops using the ((...)) construct.
  42 
  43 # These work only with Bash, version 2.04 or later.
  44 
  45 exit 0

See also Example 10-12.