Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Set hostname on Ubuntu
#!/bin/bash
# Set hostname on Ubuntu 12.04 and 14.04
usage='Usage: set-hostname.sh HOSTNAME'
[ $# -ne 1 ] && { echo "$usage" >&2; exit 1; }
echo 'Updating hostname...'
if which hostnamectl > /dev/null
then
# Ubuntu 14.04 that ships with hostnamectl
hostnamectl set-hostname "$1"
else
echo "$1" > /etc/hostname
hostname "$1"
fi
echo 'Changing /etc/hosts...'
if grep '127\.0\.1\.1' /etc/hosts > /dev/null
then
sed -i "s/127\.0\.1\.1.*/127.0.1.1 $1/g" /etc/hosts
else
echo -e "127.0.1.1\t$1" >> /etc/hosts
fi
echo "Hostname settings have been changed to $1."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment