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

nmcli -t -f STATE,WIFI,WWAN

gives way out

connected:enabled:disabled

which I would like to convert to something like

Networking: connected, Wifi: enabled, WWAN: disabled

The logical solution for me is to turn this into an array. Being a completely new bash script, I read that arrays are just regular variables and the elements are separated by spaces. My code is currently

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

which seems to apply to working in a for loop, but not if I want to request a specific item, as in $ {NMOUT []}. Clearly, I'm missing some key concept. How to access certain elements in this array?

+3
source share
2 answers

- . .

bash 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

bash: http://mywiki.wooledge.org/BashFAQ/005

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

All Articles