Shell – use printf to format output of an array

arrayprintfshell-script

I have an array that contains details about each NIC.
Each array index consists of three space-separated values.

I would like to have a nice table as output. Is there a way to assign formatting patterns to each value in an index?

so far this is what I use:

NIC_details[0]='wlp2s0 192.168.1.221 xx:xx:xx:xx:xx:xx'
NIC_details[1]='wwan0 none xx:xx:xx:xx:xx:xx'
NIC_details[2]='virbr0 192.168.122.1 00:00:00:00:00:00'

printf "%-20s\n" "${NIC_details[@]}"

Is there a way to access the values in an array index by their position $1, $2, and $3, knowing that they are space-separated, and then apply a formatting pattern for each $X position?

I have also tried

echo "$i" | column -t

but it does not bring the desired result.

Best Answer

Here's a slight modification to what you were already doing:

set -f # to prevent filename expansion
for i in ${!NIC_index[@]}
do
  printf "%-20s" ${NIC_details[i]}
  printf "\n"
done

I added a for loop to go over all of the array indexes -- that's the ${!NIC... syntax. Since it's a numeric array, you could alternatively loop directly over the indexes.

Note that I intentionally left ${NIC_details[i]} unquoted so that the shell would split the value on the spaces that you've used to separate the values. printf thus sees the 3 values and so repeats the %-20s formatting for each of them. I then add a newline after each NIC to make a nice table.

The set -f at the top is important if we leave variables unquoted; otherwise the shell will step in and attempt to glob any wildcards it sees in unquoted variables.

Sample output:

wlp2s0              192.168.1.221       xx:xx:xx:xx:xx:xx
wwan0               none                xx:xx:xx:xx:xx:xx
virbr0              192.168.122.1       00:00:00:00:00:00
Related Question