I want to write a script that will achieve the same effect as changing the hostname in raspi-config. However, I am not entirely sure what raspi-config does when the hostname is changed (via 1 System Options > S4 Hostname).

I assume that at least the following two changes are made:

  • /etc/hostname is changed
  • the line containing in /etc/hosts is changed

Is there any other change made?

2 Answers 2


As you have noted 2 files are changed.

I routinely edit these; I have a script which I run if swapping a SD Card between Pi.

# script to set Pi hostname based on Serial number
# 2021-04-17
# 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")"  # directory containing script

# CPUID=$(awk '/Serial/ {print $3}' /proc/cpuinfo | sed 's/^0*//')  #Pi4 has 16digit serial with leading '1'
CPUID=$(awk '/Serial/ {print $3}' /proc/cpuinfo | cut -c9-)

echo "Current Name" $CURRENT_HOSTNAME

# If you want to specify hostnames create a file PiSerialNo.txt with SerialNo hostname list e.g.
# e9195b37  MyPi
# If not found a unique Name based on SerialNo number will be set

NEW_HOSTNAME=$(awk /$CPUID/' {print $2}' $PDIR"/PiSerialNo.txt")
# echo "Name found" $NEW_HOSTNAME

if [ -z $NEW_HOSTNAME ]; then

    echo "hostname $NEW_HOSTNAME already set"
    if [ $(id -u) -ne 0 ]; then
      echo "Please run with sudo to change name"
    echo "Setting Name" $NEW_HOSTNAME
    echo $NEW_HOSTNAME > /etc/hostname
    sed -i "/$CURRENT_HOSTNAME/$NEW_HOSTNAME/" /etc/hosts

It would indeed appear that it is in just those two files that changes are made.

Looking at line 216 of the source code for the script:

    echo $NEW_HOSTNAME > /etc/hostname
    sed -i "s/*$CURRENT_HOSTNAME/\t$NEW_HOSTNAME/g" /etc/hosts
  • 1
    You can also use hostname for the first part, it has a man page that may be interesting.
    – goldilocks
    Oct 16, 2022 at 17:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.