Bash Brace Expansion – Fixing Brace Expansion Not Working in a Script

bashbrace-expansionshellshell-script

for i in {1..40}
do 
   echo $i
done

I got

{1..40}

and I would like to have something like

1
2
3
and so on

so I can use the variable i inside a command's parameter.

Best Answer

In bash 3.0+ (as well as zsh and ksh93), {1..40} will expand to the numbers from 1-40 (inclusive). In a POSIX shell like dash (which is typical of /bin/sh in e.g. Ubuntu), it will not work (we call this issue a "bashism").

On systems with the GNU utilities, you can use seq to accomplish this:

for i in $(seq 1 40)
do
    echo $i
done

To be more portable, you'll have to manually increment $i in a while loop:

i=1
while [ $i -le 40 ]
do
    echo $i
    i=$((i+1))
done

This portable version is also very slightly faster since it lacks the external command.

Related Question