1

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 127.0.1.1 in /etc/hosts is changed

Is there any other change made?

Greenonline
  • 2,740
  • 4
  • 23
  • 36

2 Answers2

1

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/127.0.1.1.*$CURRENT_HOSTNAME/127.0.1.1\t$NEW_HOSTNAME/g" /etc/hosts
Greenonline
  • 2,740
  • 4
  • 23
  • 36
1

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.

#!/bin/bash
# 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 CURRENT_HOSTNAME=$(hostname)

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 echo "CPUID" $CPUID

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 NEW_HOSTNAME="pi"$CPUID fi

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

Milliways
  • 59,890
  • 31
  • 101
  • 209