Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 263
McB Avatar asked Jul 30 '13 14:07

McB


2 Answers

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

like image 126
jderefinko Avatar answered Sep 30 '22 21:09

jderefinko


 ip addr | grep link/ether | awk '{print $2}'
like image 32
CloudWalker Avatar answered Sep 30 '22 19:09

CloudWalker