【发布时间】:2014-04-10 00:40:24
【问题描述】:
我有这个:
for (( count= "$WP_RANGE_START"; count< "$WP_RANGE_STOP"+1; count=count+1 ));
其中WP_RANGE_START是一个类似1的数字,WP_RANGE_STOP是一个类似10的数字。
现在这将通过 1,2,...10 逐步完成
我该怎么做才能倒数?(10,9,...1)
【问题讨论】:
我有这个:
for (( count= "$WP_RANGE_START"; count< "$WP_RANGE_STOP"+1; count=count+1 ));
其中WP_RANGE_START是一个类似1的数字,WP_RANGE_STOP是一个类似10的数字。
现在这将通过 1,2,...10 逐步完成
我该怎么做才能倒数?(10,9,...1)
【问题讨论】:
我猜你所拥有的会是镜像
for (( count="$WP_RANGE_STOP"; count >= "$WP_RANGE_START"; count=count-1 ));
但是写起来不那么麻烦的方式是
for (( count=WP_RANGE_STOP; count >= WP_RANGE_START; count-- ));
$ 在算术上下文中是不必要的。
在处理文字时,bash 具有使用大括号扩展的范围扩展功能:
for i in {0..10}; # or {10..0} or what have you
但是与变量一起使用很麻烦,因为大括号扩展发生在参数扩展之前。在这些情况下,使用算术 for 循环通常更容易。
【讨论】:
您的递增代码可以“简化”为:
for count in $(eval echo {$WP_RANGE_START..$WP_RANGE_STOP});
所以,要减量,你可以反转参数"
for count in $(eval echo {$WP_RANGE_STOP..$WP_RANGE_START});
假设您的 bash 版本为 3 或更高,您可以通过将其附加到范围来指定增量或减量,如下所示:
CHANGE=1
for count in $(eval echo {$WP_RANGE_STOP..$WP_RANGE_START..$CHANGE});
【讨论】:
for 循环是你的问题。
i=11 ; until [ $((i=i-1)) -lt 1 ] ; do echo $i ; done
10
9
8
7
6
5
4
3
2
1
你根本不需要任何 bashisms。
【讨论】: