Skip to content

Instantly share code, notes, and snippets.

@goliatone
Created March 4, 2016 18:10
Show Gist options
  • Select an option

  • Save goliatone/6b58312511b510cd5e06 to your computer and use it in GitHub Desktop.

Select an option

Save goliatone/6b58312511b510cd5e06 to your computer and use it in GitHub Desktop.
#!/bin/bash
# script to set Pi hostname based on MAC (or Serial number)
# 2015-02-22
# This script should be run as root (or with sudo) to change names
# If run by a user it will report changes, but will NOT implement them
PDIR="$(dirname "$0")"
CURRENT_HOSTNAME=$(cat /etc/hostname)
MAC=$(cat /sys/class/net/eth0/address)
# NOTE the last 6 bytes of MAC and CPUID are identical
CPUID=$(awk '/Serial/ {print $3}' /proc/cpuinfo | sed 's/^0*//')
echo "Current Name" $CURRENT_HOSTNAME
echo "MAC" $MAC
# If you want to specify hostnames create a file PiNames.txt with MAC hostname list
# b8:27:eb:01:02:03 MyPi
# If not found a unique Name based on Serial number will be set
NEW_HOSTNAME=$(awk /$MAC/' {print $2}' $PDIR"/PiNames.txt")
echo "Name found" $NEW_HOSTNAME
if [ $NEW_HOSTNAME == "" ]; then
NEW_HOSTNAME="pi"$CPUID
fi
if [ $NEW_HOSTNAME = $CURRENT_HOSTNAME ]; then
echo "Name already set"
else
echo "Setting Name" $NEW_HOSTNAME
echo $NEW_HOSTNAME > /etc/hostname
sed -i "/127.0.1.1/s/$CURRENT_HOSTNAME/$NEW_HOSTNAME/" /etc/hosts
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment