Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequences expansion and variable in bash [duplicate]

Tags:

bash

expansion

I am having a problem with builtin sequences (ie: not using seq) in Bash when the seq number is a variable. For example, this works and print me 1 2 3:

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

but this :

a=3
for i in {1..$a};do
   echo $i
done 

fail and print me {1..3} only

This works with ZSH and I know I have an alternative to make a counter thing but wondering if this is a bug or a brace expansion feature!

like image 706
Chmouel Boudjnah Avatar asked Feb 10 '11 11:02

Chmouel Boudjnah


3 Answers

In Bash, brace expansion is performed before variable expansion. See Shell Expansions for the order.

$ a=7; echo {1..3} {4..$a}
1 2 3 {4..7}

If you want to use a variable, use C-style for loops as in Shawn's answer.

like image 72
Dennis Williamson Avatar answered Nov 15 '22 01:11

Dennis Williamson


An alternative would be to use the double-parenthesis construct which allows C-style loops:

A=3
for (( i=1; i<=$A; i++ )); do
    echo $i
done
like image 30
Shawn Chin Avatar answered Nov 15 '22 03:11

Shawn Chin


$ num=3
$ for i in $( eval echo {1..$num});do echo $i;done
1
2
3
like image 4
kurumi Avatar answered Nov 15 '22 02:11

kurumi