How can I use variable in for loop digits?
for example:
num="12"
for i in {0..$num}; do
...
done
How can I use variable in for loop digits?
for example:
num="12"
for i in {0..$num}; do
...
done
Brace expansion with variables doesn't work as one would expect (see Appendix B for juicy details), i.e. {0..$num}
would only return {0..12}
literally instead of a list of number.
Try seq
instead like this:
num="12"
for i in $(seq 0 $num); do
echo $i
done
The bash manual saith,
The order of expansions is: brace expansion, tilde expansion, parameter, variable, and arithmetic expansion and command substitution (done in a left-to-right fashion), word splitting, and filename expansion.
At the time shell expands {0..$num}
(brace expansion), $num
isn't expanded (variable expansion) yet. The sequence expression a..b
needs both a
and b
to be numbers to generate a sequence, but here we have one number and one non-number (the literal string $num
). Failing this, the shell falls back to interpreting {0..$num}
literally. Then variable expansion takes over, and finally we get {0..12}
Bash
does brace expansion before variable expansion, so you will get output like {1..12}
. With use of eval
you can get it to work.
$ num=5
$ for i in {1..$num}; do echo "$i"; done
{1..5}
$ for i in $(eval echo {1..$num}); do echo "$i"; done
1
2
3
4
5
Please note: eval
is evil in disguise.