Paul L. Snyder on 19 May 2005 20:03:08 -0000

[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] bash, double for

Quoting "Michael C. Toren" <>:

> On Thu, May 19, 2005 at 02:04:31PM -0400, Dan Crosta wrote:
> >    n=`echo "$n + 1" | bc`
> You can use bash's $((..)) arithmetic substitution.  For example:
> 	echo $((n++))

One thing that can be confusing to aspiring shell progammers:

  bash$ n=3
  bash$ n=$((n++))
  bash$ echo $n

What happened here?  The trick is that '++' is the postincrement
operator, which works via side-effects. So what's really happening is:

  1.  bash reads in the command "n=3" and stores '3' in the parameter 'n'.
  2a. bash reads in the command "n=$((n++))"
  2b. bash performs arithmetic expansion on the command.  '++' means "do
      something with this variable, then increment it.  So bash replaces
      the command-line with "n=3" (the current value of n) and behind
      the scenes it increases the value store in 'n' by 1, so now '4' is
      stored in 'n'.
  2c. bash executes the command "n=3", which stores '3' in 'n'.  Whoops!
  3a. bash reads in the command "echo $n".
  3b. bash performs parameter expansion on the command, which is now
      "echo 3"
  3c. bash executes the command, echoing '3' to the output.

Here's a way around that if you just want to increment a variable:

  bash$ : $((n++))

The ':' is the null-command.  It's often used when you just want to expand
the arguments and not do anything with them.  In mct's example above, if
n=3, then the command will output '3' and change the value stored in 'n'
to '4' as a side-effect.

  bash$ echo $((++n))

may be less confusing, as it changes the value store in 'n' before it
does anything else with it.

Philadelphia Linux Users Group         --
Announcements -
General Discussion  --