【问题标题】:BASH: loop array values unlimitedBASH:循环数组值无限制
【发布时间】:2021-06-13 08:46:02
【问题描述】:

在 bash 中我想要数组让我们说:

array=(1 2 3)

然后我需要一个程序循环

x 将是 1,2,3,1,2,3...(来自数组)

我将无限次 1,2,3,4,5,6....(主循环)

我的代码:

array=(1 2 3)
while true ; do
 ((i=i+1))
 #screen -dmS plot$i -d /destinatin$x
 echo $i $x
 sleep 1
done

我不知道如何循环数组并将 $x 设置为 1,2,3,1,2,3....

【问题讨论】:

    标签: bash loops


    【解决方案1】:

    无限循环通常使用 shell 内置命令 : 生成,它在单数形式中不执行任何操作。所以如果你想在列表的元素上无限循环,你可以这样做:

    1.无限嵌套的 while-for 循环:

    while :; do for i in "${a[@]}"; do echo "${i}"; done; done
    

    2。使用索引重置

    i=0; while :; do echo "${a[i]}"; ((i=i+1)); ((i==${#a[@]})) && i=0; done
    

    2。使用模数计算:

    i=0; while :; do echo "${a[i]}"; (( i=(i+1) % ${#a[@]} )); done
    

    3.带模索引的无限 for 循环

    for ((i=0;;i++)); do echo "${a[i%${#a[@]}]}"; done
    

    【讨论】:

      【解决方案2】:

      这段代码应该可以解决你的问题:

      #!/bin/bash
      
      array=(1 2 3)
      i=0
      count_of_elements=${#array[@]} #counting the number of array elements
      
      while true; do
      rest=$(($i%$count_of_elements)) #counting rest of the division by count of array elements
      printf "${array[$rest]}," #dispay result
      i=$((i+1))
      done
      

      如果您更改输入数组(例如,如果它将是 array=(1 2 3 4 5),它也会起作用。

      【讨论】:

        猜你喜欢
        • 2014-05-04
        • 1970-01-01
        • 2013-03-26
        • 2013-04-25
        • 1970-01-01
        • 2011-12-16
        • 1970-01-01
        • 1970-01-01
        • 2016-03-06
        相关资源
        最近更新 更多