Reputation: 6310
I am trying to understand why this loop does not print a number for each arguments supplied to the script.
#!/bin/bash
for i in {1..$#}; do
echo $i
done
Instead, when supplied e.g. 3 arguments, it outputs
{1..3}
Upvotes: 0
Views: 373
Reputation: 246807
Brace expansion occurs before variable expansion
http://www.gnu.org/software/bash/manual/bashref.html#Shell-Expansions
Upvotes: 1
Reputation: 289725
The expression {}
does not accept variables.
To do so, you need to work with for example seq
. The following will make it::
#!/bin/bash
for i in $(seq 1 $#); do
echo $i
done
Note that $()
is equivalent to ``
. That is, it performs a command substitution. For example:
$ d=$(echo "hello")
$ echo $d
hello
You can see more information in Shell Programming: What's the difference between $(command) and command
.
$ ./a
$
$ ./a a b c
1
2
3
Upvotes: 3