[英]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 什么代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.