The 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 run command
and put its output here. So
echo "Today is $(date). A fine day."
will run the date
command and include its output in the argument to echo
. 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 variable var
, followed by text
(as opposed to $vartext
which means the contents of the variable vartext
).
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. The for
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 a while
loop. The expression
for ((init; check; step)); do
body
done
is equivalent to
init
while check; do
body
step
done
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 the while
loop.
Of course, this syntax is Bash-specific; classic Bourne shell only has
for variable in token1 token2 ...; do
(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:
date +'Today is %c. A fine day.'
Avoiding a process where you can is an important consideration, even though it doesn't make a lot of difference in this isolated example.)