Yotam
Yotam

Reputation: 10485

For loop using variable as condition, Bash

I am running the following bash code:

num=$(ls -1 $ini/*.ini | wc -l)
echo "Running $num simulations..."
for i in {1..$num};
do
    echo "a"
done

And I get the following output:

Running 24 simulations...
a

It should print 24 lines of 'a', but it doesn't. What should I change? Thanks!

Upvotes: 0

Views: 207

Answers (4)

ormaaj
ormaaj

Reputation: 6577

Read:

Disregard answers involving seq(1). cdarke's answer demonstrates correct iteration.

Also note that this is a bash-specific issue. Other shells with brace expansion will evaluate parameter expansions first, but there are tradeoffs.

Upvotes: 0

cdarke
cdarke

Reputation: 44354

Try:

for (( i=0; i < $num; i++ ))
do
    echo "a"
done

Upvotes: 1

Johannes Weiss
Johannes Weiss

Reputation: 54031

The curly brackets don't expand variables. You could use

for i in $(seq $num); do
    echo "a"
done

See e.g. man bash:

[...]

A sequence expression takes the form {x..y[..incr]}, where x and y are either integers or single characters, and incr, an optional increment, is an integer. When integers are supplied, the expression expands to each number between x and y, inclusive.

[...]

Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces.

[...]

Upvotes: 1

choroba
choroba

Reputation: 241828

The brace expansion only works for literals, it does not expand variables.

Possible workaround:

for i in $(seq 1 $num) ; do

Upvotes: 0

Related Questions