iSpoon
iSpoon

Reputation: 27

Raspberry Pi Bash Script for network adapter, ip addresss and Mac address

I want to have a short cut to display the adapter, IP address and Mac address. I have the following:

#! /bin/bash
for iface in $(ifconfig | grep -v "lo" | cut -d ' ' -f1| tr '\n' ' ')
do 
   ipadd=$(ip -o -4 addr list $iface | awk '{print $4}' | cut -d/ -f1)
   madd=$(ip -o link list $iface | awk '{print $17}')
   printf "$iface\t$ipadd\t$madd\n"
done
  1. The ethernet adapter doesn't show IP address and show as no such device. But if I run the command manually in bash it work and show up. The same script work correctly on my Ubuntu but not on Raspberry Pi (only manual command work). wlan0 works with no problem on Pi

  2. The MAC address doesn't work at all, but if I run the command manually ip -o link list <adapter> | awk '{print $17}') it show the Mac address correctly.

Please advise where could have gone wrong.

Update:

+++ ifconfig
+++ grep -v lo
+++ cut -d ' ' -f1
+++ tr '\n' ' '
++ for iface in $(ifconfig | grep -v "lo" | cut -d ' ' -f1| tr '\n' ' ')
+++ ip -o -4 addr list enxb827ebe7229c:
+++ awk '{print $4}'
+++ cut -d/ -f1
Device "enxb827ebe7229c:" does not exist.
++ ipadd=
+++ ip -o -4 link list enxb827ebe7229c:
+++ awk '{print $17}'
Device "enxb827ebe7229c:" does not exist.
++ madd=
++ printf 'enxb827ebe7229c:\t\t\n'
enxb827ebe7229c:        
++ for iface in $(ifconfig | grep -v "lo" | cut -d ' ' -f1| tr '\n' ' ')
+++ ip -o -4 addr list wlan0:
+++ awk '{print $4}'
+++ cut -d/ -f1
++ ipadd=192.168.1.4
+++ ip -o -4 link list wlan0:
+++ awk '{print $17}'
RTNETLINK answers: No such device
Cannot send link get request: No such device
++ madd=
++ printf 'wlan0:\t192.168.1.4\t\n'
wlan0:  192.168.1.4

If I run the command manually:

ip -o -4 link list enxb827ebe7229c | awk '{print $17}'

I get the Mac address

If I run this

ip -o addr list enxb827ebe7229c | awk '{print $4}' | cut -d/ -f1

I too will get the ipaddress correctly

Upvotes: 0

Views: 256

Answers (1)

KamilCuk
KamilCuk

Reputation: 140940

A small fix was enough:

for iface in $(ifconfig | grep -v "lo:" | cut -d ' ' -f1 | cut -d: -f1); do
     ipadd=$(ip -o -4 addr list $iface | awk '{print $4}' | cut -d/ -f1);
     madd=$(ip -o link list $iface | awk '{print $17}');
     printf "$iface\t$ipadd\t$madd\n";
done

The part ifconfig | grep -v "lo:" | cut -d ' ' -f1| tr '\n' ' ' leaves the : character in the output, so you are iterating over eth0: eth1: not over eth0 eth1. You need to remove the :, either with a simple cut -d: -f1 or tr -d: or any other mean.

Also note, as you've just discovered, the ifconfig output differs between platforms and implementations. It's better to just stick to the new ip command. Ex. ip a | sed -n '/^[^ ]*: \([^ ]*\):.*/{s//\1/;p;}'

There is no need for tr '\n' ' '. Shell interprets any whitespace character - that is tab, space or newline - as a word separator.

Upvotes: 1

Related Questions