home · contact · privacy
Enhance bookworm setup.
[config] / bookworm / setup_scripts / set_hostname_and_fqdn.sh
1 #!/bin/sh
2 # Sets hostname and optionally FQDN.
3 #
4 # Calls hostname, writes to /etc/hostname and /etc/hosts. For /etc/hosts
5 # writing follows recommendations from Debian manual at
6 # <https://www.debian.org/doc/manuals/debian-reference/ch05.en.html>
7 # (section "The hostname resolution") on how to map hostname and possibly
8 # FQDN to a permanent IP if present (we assume here any non-private IP
9 # and non-loopback IP returned by hostname -I to fulfill that criterion
10 # on our systems) or to 127.0.1.1 if not. On the reasoning for separating
11 # localhost and hostname mapping to different IPs, see
12 # <https://unix.stackexchange.com/a/13087>.
13 #
14 # Ignores IPv6s.
15 set -e
16 . ./misc.sh
17
18 expect_n_args 1 "(hostname, fqdn)" "$@"
19
20 hostname="$1"
21 fqdn="$2"
22 echo "${hostname}" > /etc/hostname
23 hostname "${hostname}"
24
25 final_ip="127.0.1.1"
26 for ip in $(hostname -I); do
27     if [ $(echo "${ip}" | grep ':' | wc -l) -eq 1 ]; then
28         continue
29     fi
30     range_1=$(echo "${ip}" | cut -d "." -f 1)
31     range_2=$(echo "${ip}" | cut -d "." -f 2)
32     if [ "${range_1}" -eq 127 ]; then
33         continue
34     elif [ "${range_1}" -eq 10 ]; then
35         continue
36     elif [ "${range_1}" -eq 172 ]; then
37         if [ "${range_2}" -ge 16 ] && [ "${range_2}" -le 31 ]; then
38             continue
39         fi
40     elif [ "${range_1}" -eq 192 ]; then
41         if [ "${range_2}" -eq 168 ]; then
42             continue
43         fi
44     fi
45     final_ip="${ip}"
46 done
47
48 echo "127.0.0.1 localhost.localdomain localhost" > /etc/hosts
49 echo "${final_ip} ${fqdn} ${hostname}" >> /etc/hosts