Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
a script for updating hostname and /etc/hosts
#!/bin/bash
if [ $USER != "root" ]; then
echo "root permission required"
exit 1
fi
if [ $# -eq 0 ]; then
echo "usage: $0 <fqdn> [<hosts_file>]"
exit 1
fi
CONFIRM=0
NEW_FQDN=$1
NEW_HOSTNAME=`echo $NEW_FQDN | awk -F '.' '{print $1}'`
NEW_DOMAINNAME=`echo $NEW_FQDN | sed -e 's/^[^\.]\+\.//g'`
if [ $# -ge 2 ]; then
HOSTS_FILE=$2
fi
cat <<EOF
* updating hostname with following information:
---------------------------
fqdn: $NEW_FQDN
hostname: $NEW_HOSTNAME
---------------------------
EOF
if [ $# -ge 2 ]; then
cat <<EOF
* adding following hosts list to /etc/hosts
---------------------------
`cat $HOSTS_FILE | sed -e 's/^/ /g'`
---------------------------
EOF
fi
if [ $CONFIRM -eq 1 ]; then
read -p "update hostname? [Y/n]: " ans
if [ "$ans" != "Y" -a "$ans" != "y" -a -n "$ans" ]; then
echo "cancelled"
exit 2
fi
echo
fi
if [ $# -le 1 ]; then
HOSTS_FILE=/tmp/hosts.local
echo "127.1.1.1 $NEW_FQDN $NEW_HOSTNAME" > $HOSTS_FILE
fi
# update new hostname
hostname $NEW_HOSTNAME
echo $NEW_HOSTNAME > /etc/hostname
# disable 127.0.1.1 line
sed -i -e "s/^\(127.0.1.1.*\)/#\1/g" /etc/hosts
# merge hosts file
# - delete previously merged hosts list
startline=`cat -n /etc/hosts | grep '# >>> start auto merge' | awk '{print $1}'`
endline=`cat -n /etc/hosts | grep '# <<< end auto merge' | awk '{print $1}'`
if [ -n "$startline" -a -n "$endline" ]; then
head -`expr $startline - 1` /etc/hosts > tmphosts
tail -n +`expr $endline + 1` /etc/hosts >> tmphosts
else
cp /etc/hosts tmphosts
fi
# - add new hosts file
echo '# >>> start auto merge' >> tmphosts
cat $HOSTS_FILE >> tmphosts
echo '# <<< end auto merge' >> tmphosts
mv tmphosts /etc/hosts
if [ $# -le 1 ]; then
rm -f $HOSTS_FILE
fi
echo "hostname updated"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment