1

the following gives me 5 hi:

for i in {1..5} ; 
do
echo hi $i
done

but when i do the following with variable, it wont:

num=5
for i in {1..$num} ; 
echo hihi $i
done

and i tried put some " " or or ' ' around, but it still doesnt give me 5 hi, please give me some advice. the result return is {1..$num}, so please tell me how to set up a proper for situation with variable. thanks.

Robert Choy
  • 105
  • 1
  • 8
  • 2
    Variable expansion takes place after braces, so you can't use them inside. You can use seq if you want to use vars. i.e `for i in $(seq 1 $num)` – 123 May 09 '17 at 10:29
  • 1
    Don't use `seq`; it's inferior to, and no more standard than, a C-style `for` loop. – chepner May 09 '17 at 11:26

1 Answers1

2

The problem is Brace Expansion happens much before Parameter Expansion, so the variable will not be expanded as you expected it to be.

Use a proper C style for-loop,

for ((i=1; i<=num; i++)); do

From man bash page, under EXPANSION section

EXPANSION

Expansion is performed on the command line after it has been split into words. There are seven kinds of expansion performed.

The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; and pathname expansion.

Inian
  • 80,270
  • 14
  • 142
  • 161