简体   繁体   English

如何在Shell脚本中将循环的输出值存储在数组中?

[英]How to store the values of the output of a loop in an array in shell scripting?

In shell scripting, I have a loop with an if condition inside a for loop. 在shell脚本中,我在for循环中有一个带if条件的循环。

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

printf statement prints the values on the output. printf语句在输出上打印值。 However, I want to store these values in an array to use inside another loop. 但是,我想将这些值存储在数组中以在另一个循环内使用。 How do I do this? 我该怎么做呢?

You initialize an array before for loop and inside for loop just keep appending to array. 您之前初始化数组for loop和内部for loop只是不断追加到数组。

Code skeleton: 代码框架:

# initializing an array
arr=()
for ((i=0; i<=5; i++ )) do if ((...)) then arr+=($i); printf .... fi done
  • arr=() creates a new array arr=()创建一个新数组
  • arr+=($i) appends/adds an element into array arr arr+=($i)向数组arr追加/添加一个元素

Here's the solution: 解决方法如下:

#!/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

What code does 什么代码

  • creates and empty array 创建并清空数组
  • creates an index-counter for array 为数组创建索引计数器
  • stores result of output printf command in array at corresponding index (the backquote tells interpreter to do that) 将输出printf命令的结果存储在数组中的相应索引处(反引号告诉解释器执行该操作)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM