【问题标题】:How to store the values of the output of a loop in an array in shell scripting?如何将循环输出的值存储在 shell 脚本中的数组中?
【发布时间】:2014-01-29 12:58:19
【问题描述】:

在 shell 脚本中,我在 for 循环中有一个带有 if 条件的循环。

for ((init; condition; increment))
do
    if ((condition)) then
        printf ...
    fi
done

printf 语句在输出中打印值。但是,我想将这些值存储在一个数组中以在另一个循环中使用。我该怎么做?

【问题讨论】:

  • Joker,请在编辑语法之前更加注意所使用的语言。您的更改对 C# 完全有效,但对 Unix shell 脚本则不然。

标签: arrays shell scripting


【解决方案1】:

您在for loop 之前和for loop 内部初始化一个数组,只需继续追加到数组即可。

代码骨架:

# initializing an array
arr=()
for ((i=0; i<=5; i++ )) do if ((...)) then arr+=($i); printf .... fi done
  • arr=() 创建一个新数组
  • arr+=($i) 将元素追加/添加到数组 arr

【讨论】:

    【解决方案2】:

    解决办法如下:

    #!/bin/bash
    
    data=() #declare an array outside the scope of loop
    idx=0   #initialize a counter to zero
    for i in {53..99} #some random number range
    do
        data[idx]=`printf "number=%s\n" $i` #store data in array
        idx=$((idx+1)) #increment the counter
    done
    echo ${data[*]} #your result
    

    代码的作用

    • 创建并清空数组
    • 为数组创建索引计数器
    • 将输出 printf 命令的结果存储在数组中相应索引处(反引号告诉解释器这样做)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-12
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-04
      • 1970-01-01
      • 2021-09-30
      相关资源
      最近更新 更多