Ubuntu – Store output of command into the array

scripts

This is command: pdc status -a 2>&1 | grep 'okay' It gives the following output

[okay     ]: you are currently listening: 33
[okay     ]: you are currently listening: 22
[okay     ]: you are currently listening: 11

I have written this command in shell scrip file. But I want to store the output of this command into the array for some processing on each of the index value in the array.

How can I store the output of this command into the array?

Best Answer

If you just want the numbers at the end of each line:

numbers=( $(pdc ... | grep -oP 'okay.+?\K\d+$') )

If you want to store each line into the array

mapfile -t lines < <(pdc ...)

To retrieve the data from the arrays:

for (( i=0; i<${#numbers[@]}; i++ )); do echo ${numbers[i]}; done
echo
printf "%s\n" "${lines[@]}"
33
22
11

[okay   ]: you are currently listening: 33
[okay   ]: you are currently listening: 22
[okay   ]: you are currently listening: 11
Related Question