Arrays 如何在shell脚本中将循环返回的值存储在数组中?
在shell脚本中,我有一个带有if的循环 for循环中的条件Arrays 如何在shell脚本中将循环返回的值存储在数组中?,arrays,shell,scripting,Arrays,Shell,Scripting,在shell脚本中,我有一个带有if的循环 for循环中的条件 for i in val1 val2 do if ((condition)) then printf ... fi done 此循环返回正确的输出,即数字列表。但是,我想将这些数字存储在 在另一个循环中使用的数组。我该怎么办 这个 我想知道如何将printf语句返回的值存储在数组中。以下是解决方案: #!/bin/bash data=() #declare an array outside the
for i in val1 val2
do
if ((condition)) then
printf ...
fi
done
此循环返回正确的输出,即数字列表。但是,我想将这些数字存储在
在另一个循环中使用的数组。我该怎么办
这个
我想知道如何将printf语句返回的值存储在数组中。以下是解决方案:
#!/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命令的结果存储在相应索引的数组中(后引号告诉解释器这样做)