【问题标题】:How to store values returned by a loop in an array in shell scripting?如何将循环返回的值存储在 shell 脚本中的数组中?
【发布时间】:2014-01-29 14:55:14
【问题描述】:

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

for i in val1 val2
do
    if ((condition)) then
        printf ...
    fi
done

这个循环返回正确的输出,它是一个数字列表。但是,我想将这些数字存储在 在另一个循环中使用的数组。我该怎么办 这个?

我想知道如何将 printf 语句返回的值存储在一个数组中。

【问题讨论】:

    标签: arrays shell scripting


    【解决方案1】:

    解决办法如下:

    #!/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
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      • 2011-03-04
      • 2021-02-23
      • 1970-01-01
      • 2021-09-05
      • 2016-10-18
      相关资源
      最近更新 更多