View Single Post
  #1   (View Single Post)  
Old 29th September 2008
spiderpig spiderpig is offline
Port Guard
 
Join Date: May 2008
Posts: 29
Default incrementing within a shell script?

I know that the following:
Code:
#!/bin/sh
i=0
i=$(($i + 1))
echo $i
is the same as the following:
Code:
#!/bin/sh
i=0
i=$(expr $i + 1)
echo $i
My understanding is that a new shell is spawned to execute ($i + 1) or expr $i + 1, but why are the parentheses needed in ($i + 1)? The best answer I can figure is that the statement:
Code:
i=$($i + 1)
is syntactically wrong because somehow $i in the spawned shell is being interpreted as the name of some application which is to be run. Adding the inner set of parentheses somehow forces the shell to treat the argument ($i + 1) as an expression to be evaluated. I had convinced myself that this was a plausible answer for quite some time until I tried it manually at a shell prompt:
Code:
$ i=1
$ echo $i
1
$ sh ($i + 1)
sh: 1: No such file or directory
So why are the inner set of parentheses required in x=$(($i + 1))?

Thanks!
Reply With Quote