带有变量 bash 的降序循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4679188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:04:59  来源:igfitidea点击:

descending loop with variable bash

bash

提问by LanceBaynes

$ 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?

为什么它不起作用?
我找不到任何在谷歌搜索降序循环的例子......,甚至没有变量。为什么?

回答by Roy

You should specify the increment with seq:

您应该使用 seq 指定增量:

seq $FROMHERE -1 1

回答by Paused until further notice.

Bash has a forloop syntax for this purpose. It's not necessary to use the external sequtility.

for为此,Bash 有一个循环语法。没有必要使用外部seq实用程序。

#!/bin/bash

FROMHERE=10

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

回答by Shakiba Moshiri

loop down with for (stop play)

循环使用 for(停止播放)

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

使用while:第一步

AAA=10

then

然后

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

or: "AAA--" into while

或:“AAA--”进入while

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

"sleep 1" isn't need

不需要“睡眠 1”

回答by Jürgen H?tzel

You might prefer Bash builtinShell Arithmetic instead of spawning external seq:

您可能更喜欢 Bash内置Shell Arithmetic 而不是产生外部seq

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