Create an array with all network interfaces in bash
Here is a solution, assign the list and then add item to it:
#!/bin/bash
array_test=()
for iface in $(ifconfig | cut -d ' ' -f1| tr ':' '\n' | awk NF)
do
printf "$iface\n"
array_test+=("$iface")
done
echo ${array_test[@]}
If you want the output displayed one item per line:
for i in "${array_test[@]}"; do echo "$i"; done
To remove localhost from output:
if [ "$iface" != "lo" ]
then
array_test+=("$iface")
fi
My try:
readarray -t interfaces < <(ip l | awk -F ":" '/^[0-9]+:/{dev=$2 ; if ( dev !~ /^ lo$/) {print $2}}')
for i in "${interfaces[@]// /}" ; do echo "$i" ; done
bash
will construct an array from any white-space delimited (spaces, tabs, newlines) list you give it. e.g. array=(a b c)
. We can use command substitution ($()
) to generate such a white-space delimited list. For example:
$ ifaces=( $(ip addr list | awk -F': ' '/^[0-9]/ {print $2}') )
and now print out the array we just created:
$ declare -p ifaces
declare -a ifaces=([0]="lo" [1]="eth0" [2]="eth1" [3]="br1" [4]="br0" [5]="ppp0")
To exclude lo
:
$ ifaces=( $(ip addr list | awk -F': ' '/^[0-9]/ && $2 != "lo" {print $2}') )
$ declare -p ifaces
declare -a ifaces=([0]="eth0" [1]="eth1" [2]="br1" [3]="br0" [4]="ppp0")
If you really want to use ifconfig
rather than ip
, try this:
ifaces=( $(ifconfig | awk -F':' '/^[^ ]*: / && $1 != "lo" {print $1}') )