【问题标题】:In Bash: Can I treat the list of args in a for loop as a list?在 Bash 中:我可以将 for 循环中的 args 列表视为列表吗?
【发布时间】:2012-07-12 08:42:42
【问题描述】:

我可以将 for 循环中的 args 列表视为列表吗?我可以使用列表索引访问列表中的元素吗? 运行这个伪代码:

#!/bin/bash
for i in 1 2; do
    j=the next element in the for loop
    echo current is $i and next is $j
done

输出应该是第一次迭代:

当前为 1,下一个为 2

循环的第二次迭代会是什么?

【问题讨论】:

    标签: bash for-loop arguments


    【解决方案1】:

    试试这个代码:

    declare -a data=(1 2)
    
    for (( i = 0 ; i < ${#data[@]} ; i++ )) do
        elem=${data[$i]}
        j=$((i+1))
        nextElem=${data[$j]}
        echo current is $i $elem and next is $j $nextElem
    done
    

    相关:

    【讨论】:

      【解决方案2】:

      我觉得 bash 的人总是追求最复杂的事情。你也可以一起住吗:

      # Let's say we want to access elements 1,3,3,7 in this order
      cur=$1
      for next in "$3" "$3" "$7"
      do
          printf "cur: %s, next: %s\n" "$cur" "$next"
          cur=$next
      done
      

      What will it be for thesecondlast iteration of the loop?

      如果你不能回答这个问题,我也一样。这通常意味着你想得太复杂了。我认为更简单的我上面的版本没有以非常自然的方式有这个角落,因为它的不同之处在于最后一次迭代“丢失”了。

      【讨论】:

        【解决方案3】:

        没有(实用的)方法可以监视for 循环中的下一个元素将是什么。您必须将值存储在其他地方和/或使用不同类型的循环。

        您可以使用位置参数或数组。

        位置参数保证不稀疏。

        set -- {a..f}
        n=1
        
        while ((n<=$#)); do
            printf 'cur: %s%.s%s\n' "${!n}" $((++n)) ${!n:+", next: ${!n}"}
        done
        

        Bash 数组是稀疏的。如果您不直接使用 for 循环对值进行迭代,则应使用索引。

        arr=({a..f}) idx=("${!arr[@]}")
        
        while ((n<${#idx[@]})); do
            printf 'cur: %s%s\n' "${arr[idx[n]]}" ${idx[++n]:+", next: ${arr[idx[n]]}"}
        done
        

        即使您认为可以保证元素是连续的,这种方法也不错。

        两个示例的输出:

        cur: a, next: b
        cur: b, next: c
        cur: c, next: d
        cur: d, next: e
        cur: e, next: f
        cur: f
        

        【讨论】:

          猜你喜欢
          • 2016-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-11
          • 2021-10-11
          • 2012-02-11
          • 1970-01-01
          相关资源
          最近更新 更多