开发者

descending loop with variable bash

$ 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 ex开发者_StackOverflow中文版amples searching google for a descending loop..., not even variable in it. Why?


You should specify the increment with seq:

seq $FROMHERE -1 1


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


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

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜