I frequently write for-loops in bash with the well-known syntax:
for i in {1..10} [...]
Now, I'm trying to write one where the top is defined by a variable:
TOP=10
for i in {1..$TOP} [...]
I've tried a variety of parens, curly-brackets, evaluations, etc, and typically get back an error "bad substitution".
How can I write my for-loop so that the limit depends on a variable instead of a hard-coded value?
You can use for loop like this to iterate with a variable $TOP
:
for ((i=1; i<=$TOP; i++))
do
echo $i
# rest of your code
done
If you have a gnu system, you can use seq
to generate various sequences, including this.
for i in $(seq $TOP); do
...
done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With