1

I would like to have a bash loop function like below, with decreasing sequency:

for i in {8..2}
do
...
done

And the 8 and 2 can be set as a variable, like:

start=$1
end=$2

for i in {$start..$end}
do
...
done

But seem this dose not work. How can I do this?

Thanks for all the quick answers, later I found the answer here. descending loop with variable bash

solution:

start=$1
end=$2

for i in `seq $start -1 $end`
do
...
done

Thanks~

Community
  • 1
  • 1
zhihong
  • 1,808
  • 2
  • 24
  • 34
  • 1
    Thanks, but one difference, I need a decrease seq as {8..2},but not {2..8}, and the `seq $start $end` dose not work. – zhihong Aug 01 '13 at 16:23

3 Answers3

1
$ start=8; end=2; for ((i = start; i >= end; i--)); do echo "${i}"; done
8
7
6
5
4
3
2
Adrian Frühwirth
  • 42,970
  • 10
  • 60
  • 71
0

Nope. But here is a workaround

start=$1
end=$2

for i in $(seq $start $end)
do
...
done
the.malkolm
  • 2,391
  • 16
  • 16
0

You can't use variable substitution there since the {n..m} is already one. Try using seq:

for i in `seq $start $end`
do
  ...
done

Alternatively you could do a while loop incrementing the loop variable by manually:

i=$start
while [ $i -lt $end ]; do
  ...
  : $[i++]
done

Although with while you have to be aware if $start is smaller or greater than $end

fejese
  • 4,601
  • 4
  • 29
  • 36