Bash Shell Script – Using Integer Variable in Brace Expansion

bashforshellshell-script

I have the following bash script:

#!/bin/bash

upperlim=10

for i in {0..10}
do
echo $i
done

for i in {0..$upperlim}
do
echo $i
done

The first for loop (without the variable upperlim in the loop control) works fine, but the second for loop (with the variable upperlim in the loop control) does not. Is there any way that I can modify the second for loop so that it works? Thanks for your time.

Best Answer

The reason for this is the order in which things occur in bash. Brace expansion occurs before variables are expanded. In order to accomplish your goal, you need to use C-style for loop:

upperlim=10

for ((i=0; i<=upperlim; i++)); do
   echo "$i"
done
Related Question