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
  • 45,869
  • 10
  • 83
  • 118
LanceBaynes
  • 1,313
  • 6
  • 16
  • 23

4 Answers4

21

You should specify the increment with seq:

seq $FROMHERE -1 1
Roy
  • 43,028
  • 2
  • 26
  • 25
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
  • 16,647
  • 23
  • 89
  • 161
Dennis Williamson
  • 324,833
  • 88
  • 366
  • 429
4

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

i=10
while (( i >= 1 )); do
    echo $(( i-- ))
done
Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
Jürgen Hötzel
  • 17,806
  • 3
  • 40
  • 57
3

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
  • 16,284
  • 2
  • 23
  • 38