I'm trying to get the MAC address as a variable in Linux, but it rarely works

McB picture McB · Jul 30, 2013 · Viewed 13.6k times · Source

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.

Answer

jderefinko picture jderefinko · Jul 30, 2013

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 :)