简体   繁体   English

Shell脚本:将循环输出存储在单独的数组中

[英]Shell Scripting: Store loop output in separate array

I got the following script in which I am receiving sensor data from a host in a network. 我得到了以下脚本,其中我从网络中的主机接收传感器数据。 The data which I am receiving shall be stored in a separate array, called output , so that I can keep on working with the array output after the loop is finished. 我接收的数据应存储在一个单独的数组中,称为output ,以便在循环结束后继续处理数组输出。 Currently the loop if overwriting the data which is stored in output, every time a new sensor data is received. 当前,每次接收到新的传感器数据时,循环都会覆盖存储在输出中的数据。

declare -a sensorData=(
    "1.3.6" #Data1
    "1.3.6" #Data2
)

declare -a output=()

for i in "${sensor[@]}"
do
    output=$(snmpget -v "snmpversion" -c  "ipaddress" "$i")
    echo $output
done

So the values I get from the snmpget command shall be stored in the array output . 因此,我从snmpget命令获得的值应存储在数组output

The idea is right, but you just need to enclose the command substitution $(..) output to the array you defined. 这个想法是正确的,但是您只需要将命令替换$(..)输出封装到您定义的数组中即可。 The += operator allows you to append the snmpget output to the array in each iteration. +=运算符允许您在每次迭代中将snmpget输出附加到数组。

output+=( $(snmpget -v "snmpversion" -c  "ipaddress" "$i") )

Then you can loop over the array to get the values stored. 然后,您可以遍历数组以获取存储的值。

for val in "${output[@]}"; do
    printf "%s\n" "$val"
done

If you are worried about IFS and how the shell splits the each of the command output lines into the array, you can leave it to mapfile command, available in recent versions of bash (v4.0 or more I guess) 如果您担心IFS以及shell如何将每条命令输出行拆分到数组中,则可以将其留给mapfile命令,该文件在最新版本的bash可用(我猜是v4.0或更高版本)

mapfile -t output < <(snmpget -v "snmpversion" -c  "ipaddress" "$i")

and then run the loop over the output array as before. 然后像以前一样在输出数组上运行循环。 However this does not apply when you want to append to the array, but just run the command once. 但是,当您要追加到数组时,这仅适用于运行命令一次。

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

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