I have two questions and could use some help understanding them.
What is the difference between
${}
and$()
? I understand that()
means running command in separate shell and placing$
means passing the value to variable. Can someone help me in understanding this? Please correct me if I am wrong.If we can use
for ((i=0;i<10;i++)); do echo $i; done
and it works fine then why can't I use it aswhile ((i=0;i<10;i++)); do echo $i; done
? What is the difference in execution cycle for both?
$()
means: "first evaluate this, and then evaluate the rest of the line".Ex :
will be interpreted as
On the other hand
${}
expands a variable.Ex:
will be interpreted as
I'm afraid the answer is just that the bash syntax for
while
just isn't the same as the syntax forfor
.your understanding is right. For detailed info on {} see bash ref - parameter expansion
'for' and 'while' have different syntax and offer different styles of programmer control for an iteration. Most non-asm languages offer a similar syntax.
With while, you would probably write
i=0; while [ $i -lt 10 ]; do echo $i; i=$(( i + 1 )); done
in essence manage everything about the iteration yourselfThe syntax is token-level, so the meaning of the dollar sign depends on the token it's in. The expression
$(command)
is a modern synonym for`command`
which stands for command substitution; it means runcommand
and put its output here. Sowill run the
date
command and include its output in the argument toecho
. The parentheses are unrelated to the syntax for running a command in a subshell, although they have something in common (the command substitution also runs in a separate subshell).By contrast,
${variable}
is just a disambiguation mechanism, so you can say${var}text
when you mean the contents of the variablevar
, followed bytext
(as opposed to$vartext
which means the contents of the variablevartext
).The
while
loop expects a single argument which should evaluate to true or false (or actually multiple, where the last one's truth value is examined -- thanks Jonathan Leffler for pointing this out); when it's false, the loop is no longer executed. Thefor
loop iterates over a list of items and binds each to a loop variable in turn; the syntax you refer to is one (rather generalized) way to express a loop over a range of arithmetic values.A
for
loop like that can be rephrased as awhile
loop. The expressionis equivalent to
It makes sense to keep all the loop control in one place for legibility; but as you can see when it's expressed like this, the
for
loop does quite a bit more than thewhile
loop.Of course, this syntax is Bash-specific; classic Bourne shell only has
(Somewhat more elegantly, you could avoid the
echo
in the first example as long as you are sure that your argument string doesn't contain any%
format codes:Avoiding a process where you can is an important consideration, even though it doesn't make a lot of difference in this isolated example.)