dn3s
dn3s

Reputation: 35

(bash) How to access chunks of command output as discrete array elements?

nmcli -t -f STATE,WIFI,WWAN

gives the output

connected:enabled:disabled

which I'd like to convert to something like

Networking: connected, Wifi: enabled, WWAN: disabled

The logical solution to me is to turn this into an array. Being quite new to bash scripting, I have read that arrays are just regular variables and the elements are separated by whitespace. Currently my code is

declare -a NMOUT=$(nmcli -t -f STATE,WIFI,WWAN nm | tr ":" "\n")

which seems to sort of work for a for loop, but not if i want to ask for a specific element, as in ${NMOUT[]}. Clearly I am missing out on some key concept here. How do I access specific elements in this array?

Upvotes: 3

Views: 249

Answers (2)

jordanm
jordanm

Reputation: 35014

Ignacio Vazquez-Abrams provided a much better solution for creating the array. I will address the posted question.

Array's in bash are indexed by integers starting at 0.

"${NMOUT[0]}" # first element of the array
"${NMOUT[2]}" # third element of the array
"${NMOUT[@]}" # All array elements
"${NMOUT[*]}" # All array elements as a string

The following provides good information on using arrays in bash: http://mywiki.wooledge.org/BashFAQ/005

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799490

IFS=: read -a NMOUT < <(nmcli -t -f STATE,WIFI,WWAN)

Upvotes: 2

Related Questions