【问题标题】:Reversing a bash for loop反转 bash for 循环
【发布时间】: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)

【问题讨论】:

    标签: linux bash for-loop


    【解决方案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 循环通常更容易。

    【讨论】:

      【解决方案2】:

      您的递增代码可以“简化”为:

      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}); 
      

      【讨论】:

        【解决方案3】:

        for 循环是你的问题。

        i=11 ; until [ $((i=i-1)) -lt 1 ] ; do echo $i ; done
        

        输出

        10
        9
        8
        7
        6
        5
        4
        3
        2
        1
        

        你根本不需要任何 bashisms。

        【讨论】:

          猜你喜欢
          • 2018-05-20
          • 1970-01-01
          • 1970-01-01
          • 2021-04-24
          • 1970-01-01
          • 1970-01-01
          • 2021-12-30
          • 2018-01-05
          • 2018-02-23
          相关资源
          最近更新 更多