Count network interfaces in Bash
It is possible using either a combination of grep
and wc
, or using awk
First approach, using grep
:
ifconfig | grep "^tun" | wc -l
This will pipe the output of ifconfig
through grep, match all lines starting with the string tun
(this is accomplished using the "anchor" indicator ^
), and then use wc
to count the lines which grep
output as matched.
As pointed out by @schaiba, it is even possible without resorting to wc
by virtue of grep
's -c
option, which will count all matched lines by itself:
ifconfig | grep -c "^tun"
Second approach, using awk
:
ifconfig | awk 'BEGIN {tuns=0}; /^tun/ {tuns++}; END {print tuns}'
This will pipe the output to awk
. The awk
program, enclosed between single quotes ' ... '
, does the following:
- at the beginning (
BEGIN { ... }
), initialize an internal varibletuns
, which we will use for book-keeping, as 0 - in the main loop, for every line encountered that starts with the string
tun
(indicated by the regular expression/^tun/
), increase the countertuns
- after the input is finished, (
END { ... }
), output the resulting value oftuns
You probably don't need ifconfig
(or ip
) for this. The interfaces are listed in /sys/class/net
:
% ls /sys/class/net
eth0 lo tun0 tun1 tun2 wlan0
So, you can count the directories there, with something like:
$ printf "%s\n" /sys/class/net/tun* | wc -l
3