3

Is it possible to change the host name before the first boot? I've tried changing the name in /etc/hostname, but then the Pi doesn't boot properly. Is there something else that needs to be done?

This is intended for a Raspberry Pi running Raspbian/Raspberry Pi OS (lite) that is headless and connected by Ethernet. I'd like to be able to connect to the Raspberry Pi using ssh. (I have verified that if I don't change the host name I am able connect with ssh.)

2
  • "then the Pi doesn't boot properly." -> This shouldn't happen, methinks, but oh well. Have a look at man 5 hostname and the suggestion about using systemd-firstboot (then read man systemd-firstboot); the idea is that you mount the root filesystem somewhere (with systemd available) and use that to tweak the image without having to run the system in it. If it works out, please leave an answer of your own! – goldilocks Aug 30 '20 at 16:43
  • 2
    You need to change /etc/hostname and /etc/hosts. – Dougie Aug 30 '20 at 17:37
4

To translate the script from Milliways in his answer, change the name in /etc/hostname as you already have done and add or change the entry 127.0.1.1 raspberrypi in /etc/hosts to the new hostname.

0

It is certainly possible on a Linux computer (which can be a Pi)

The following code fragment is from one of my scripts; depending on how you implement this paths etc would need to be set.

CURRENT_HOSTNAME=$(cat /etc/hostname)

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

You are unlikely to find any existing code, but if I wanted to do this I would loop mount the image and edit it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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