8

I'm using the following code to get the MAC address of eth0 into a variable for use in a filename, but it rarely every works. It isn't that it NEVER works, it is just unpredictable.

ntpdate -b 0.centos.pool.ntp.org
DATE=$(date +%s)
MAC=$(ifconfig eth0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}' | sed 's/://g')
cp logfile logfilecp-$MAC-$DATE

Now, it seems to work less-frequently if I use the ntpdate line, but regardless, it is wholly unpredictable. Anyone have any idea what I could do to make this work better? I end up with a filename like

logfile--1375195808.bz2

New info

I've got the script setup to run as a cronjob (crontab -e). I notice that when it runs as a cronjob, it doesn't get the MAC, but when I run it manually ./runscript.bash it does get the MAC. Hopefully someone knows why this might be causing it.

Thanks.

McB
  • 1,082
  • 1
  • 18
  • 36
  • careful with that. you might also capture IPv6 addresses. you should further filter by looking for `HWaddr` – Marc B Jul 30 '13 at 14:58
  • When it fails, what does `ifconfig eth0` show? – Barmar Jul 30 '13 at 14:58
  • ifconfig shows seems fine, it shows the MAC address. I just noticed something new, have added it to the main post. – McB Jul 30 '13 at 15:01

2 Answers2

32

Try an easier method to get you mac address than through ifconfig, i.e.

cat /sys/class/net/eth0/address

I've tested it in shell (not through script) and works like a charm :

TEST=`cat /sys/class/net/eth0/address`
touch /tmp/blabla-$TEST

EDIT for your second problem

in you cron script, add the full path of the binaries you're using (i.e. /sbin/ifconfig), or use my method as above :)

jderefinko
  • 647
  • 4
  • 6
5
 ip addr | grep link/ether | awk '{print $2}'
CloudWalker
  • 313
  • 4
  • 12