Bash variable loop down

$ cat fromhere.sh
#!/bin/bash

FROMHERE=10

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

Why is this not working?
I cannot find google search examples for a downward loop ... not even a variable in it. Why?

+3
source share
4 answers

You must specify the increment with seq:

seq $FROMHERE -1 1
+14
source

Bash has loop syntax forfor this purpose. No need to use an external utility seq.

#!/bin/bash

FROMHERE=10

for ((i=FROMHERE; i>=1; i--))
do
    echo $i
done
+7
source

You may prefer Bash's built-in arithmetic shell instead of spawning external seq:

i=10
while (( i >= 1 )); do
    echo $(( i-- ))
done
+1
source

loop down with for (stop playback)

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

c: first step

AAA=10

then

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

or: "AAA--" during

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

"sleep 1" is not needed

+1
source

Source: https://habr.com/ru/post/1785166/


All Articles