You are not logged in.

#1 2011-06-18 15:49:20

I'mGeorge
Member
Registered: 2011-03-23
Posts: 150

[SOLVED] problem using variable in "for do" loop statement

As 'm fairly new to scripting in linux there are still many things I don't know about the regular syntax. So I've made a script where in a variable $nb I retain the number of lines from the result of a series of commands. I have to use a variable as the number of lines from the output is not the same all the time.

To finish my script I need to use a for loop something like this

for i in {1..$nb}
do
echo "bla bla bla $i"
done

the thing is if $nb, for example, has the value 29 it outputs

bla bla bla {1..29}

without doing any loop.

So how can I use a variable, to define the edge of an interval in a for statement ?

Last edited by I'mGeorge (2011-06-18 16:19:16)


I've first installed Arch in March

Offline

#2 2011-06-18 16:00:56

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: [SOLVED] problem using variable in "for do" loop statement

Piece of my code:

range=$( seq $1 $(($1+$2-1)) );
for y in $range;

Offline

#3 2011-06-18 16:18:42

I'mGeorge
Member
Registered: 2011-03-23
Posts: 150

Re: [SOLVED] problem using variable in "for do" loop statement

thanks karol it works like a charm using

range=$(seq 1 $nb)

I've first installed Arch in March

Offline

#4 2011-06-18 16:29:35

Ramses de Norre
Member
From: Leuven - Belgium
Registered: 2007-03-27
Posts: 1,289

Re: [SOLVED] problem using variable in "for do" loop statement

Your original code does work in zsh, just not in bash.

Offline

#5 2011-06-18 17:49:14

falconindy
Developer
From: New York, USA
Registered: 2009-10-22
Posts: 4,111
Website

Re: [SOLVED] problem using variable in "for do" loop statement

The sanctioned method in Bash is using a C style for loop:

for ((i=0; i<nb;i++)); do
...
done

Because brace expansion is performed before parameter expansion, a range like {1..$nb} will fail.

Offline

Board footer

Powered by FluxBB