Well, my new favorite approach is to pipe ifconfig
into a single sed
command 🙂
So, how does it work? Well, there are two filters (aka scripts, ie the parameters after the -e
flags). The first one, s/:127\.0\.0\.1 //g'
, simply strips out all occurrences of the local loopback address (127.0.0.1) – this can be left out if you want to include the loopback address in the results. And the second filter, 's/ *inet addr:\([0-9.]\+\).*/\1/gp'
matches all lines with IP addresses, strips all but the IP address itself, and prints the matching line (note the ‘p
‘ at the end of the filter, which works in with the -n
flag at the stared of the sed
command).
Obviously that explanation is only meant to be a brief summary. You should consult the sed
manual is you’re still unsure of how / why this works… or post a question below 🙂
Just for comparison, here’s some examples of how others do the same thing:
- Read UNIX/Linux system IP address in a shell script
ifconfig | grep ‘inet addr:’| grep -v ‘127.0.0.1’ |
cut -d: -f2 | awk ‘{ print $1}’Notice that this one uses an incorrect loopback filter (
'127.0.0.1'
should be':127\.0\.0\.1 '
) and yet my new favorite is still shorter 😉 - Parsing IP Address from ifconfig
ifconfig eth0 | grep “inet” | awk ‘{print $2}’ | awk -F: ‘{print $2}’
Pretty reasonable, but two more pipes than mine 🙂
- Setting up a 6to4 IPv6 tunnel with Debian
ifconfig $EXTIF | grep ‘inet addr’ | cut -d : -f2 | cut -d ‘ ‘ -f1
This is almost identical to how I used to do it – before I became familiar with
sed
;)
Advance (sic) Linux commands
ifconfig | grep -vw inet6 | grep -w inet | cut -d : -f 2 | cut -d \ -f 1Ok, but a little bit redundant.
ifconfig eth0 and awk and grep
ifconfig eth0 | head -n 2 \
| sed ‘N;s/\n/ /;N;s/\n/ /’ | awk ‘{print $7 ” ” $9 ” ” $5}’ \
| sed -e ‘s/addr://g’ -e ‘s/Mask://g’
Recent Comments