简体   繁体   中英

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. 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 .

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.

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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