RiftOut RiftOut - 1 month ago 12
Bash Question

Shell Scripting: Store loop output in seperate array

I got the following script in which I am reveiving sensor data from a host in a network. The data which I am receiving shall be stored in a seperate 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
.

Answer Source

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