Skip to content

Instantly share code, notes, and snippets.

@npow
Created June 21, 2013 22:19
Show Gist options
  • Save npow/5834770 to your computer and use it in GitHub Desktop.
Save npow/5834770 to your computer and use it in GitHub Desktop.
http://linuxshia.wordpress.com/2012/07/17/update-etchosts-automatically-on-a-dhcp-network/ If you happen to run your linux system on a virtualized env and you happen to have a DHCP netwotk config you can use a script like the one below to update your hosts file in order for it to use its assigned IP everytime it boots [or whenever you want]. I c…
#!/bin/bash
# Automatically replacing /etc/hosts eth[x] IP with new assigned one from DHCP
IFACE=(0 1 2 3 4 5 6 7 8 9)
x=0
while [ $x != ${#IFACE[@]} ] ; do
ifconfig eth${IFACE[$x]} 1>/dev/null 2>&1
if [ $? -eq 0 ] ; then
eth="eth${IFACE[$x]}"
break
else
let "x = x + 1"
continue
fi
done
NEW_IP=`ip addr list $eth | grep "inet " | cut -d ' ' -f 6 | cut -d / -f 1`
CURR_IP=`cat /etc/hosts | head -n 1 | cut -f 1`
HOSTNAME=`hostname`
if [ $NEW_IP == $CURR_IP ] ; then
exit 0
else
if [ -z $CURR_IP ] ; then
sed -r "s/\t{1,}$HOSTNAME/$NEW_IP\t$HOSTNAME/g" /etc/hosts > /tmp/hosts
else
sed -r "s/$CURR_IP/$NEW_IP/g" /etc/hosts > /tmp/hosts
fi
fi
mv -f /tmp/hosts /etc/hosts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment