9
$ cat fromhere.sh
#!/bin/bash

FROMHERE=10

for i in $(seq $FROMHERE 1)
do
echo $i
done
$ sh fromhere.sh
$ 

Why doesn't it works?
I can't find any examples searching google for a descending loop..., not even variable in it. Why?

ajreal
  • 46,720
  • 11
  • 89
  • 119
LanceBaynes
  • 1,393
  • 6
  • 16
  • 23

4 Answers4

22

You should specify the increment with seq:

seq $FROMHERE -1 1
Roy
  • 43,878
  • 2
  • 26
  • 26
17

Bash has a for loop syntax for this purpose. It's not necessary to use the external seq utility.

#!/bin/bash

FROMHERE=10

for ((i=FROMHERE; i>=1; i--))
do
    echo $i
done
MarcoS
  • 17,323
  • 24
  • 96
  • 174
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
4

loop down with for (stop play)

for ((q=500;q>0;q--));do echo $q ---\>\ `date +%H:%M:%S`;sleep 1;done && pkill mplayer
500 ---> 18:04:02
499 ---> 18:04:03
498 ---> 18:04:04
497 ---> 18:04:05
496 ---> 18:04:06
495 ---> 18:04:07
...
...
...
5 ---> 18:12:20
4 ---> 18:12:21
3 ---> 18:12:22
2 ---> 18:12:23
1 ---> 18:12:24

pattern :

for (( ... )); do ... ; done

example

for ((i=10;i>=0;i--)); do echo $i ; done

result

10
9
8
7
6
5
4
3
2
1
0

with while: first step

AAA=10

then

while ((AAA>=0));do echo $((AAA--));sleep 1;done

or: "AAA--" into while

while (( $((AAA-- >= 0)) ));do echo $AAA;sleep 1;done

"sleep 1" isn't need

Shakiba Moshiri
  • 21,040
  • 2
  • 34
  • 44
4

You might prefer Bash builtin Shell Arithmetic instead of spawning external seq:

i=10
while (( i >= 1 )); do
    echo $(( i-- ))
done
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Jürgen Hötzel
  • 18,997
  • 3
  • 42
  • 58