home · contact · privacy
3f95590bce3b4ff47abeb206cdc60bd36fadabe0
[config] / buster / 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 set -e
14
15 hostname="$1"
16 fqdn="$2"
17 if [ "${hostname}" = "" ]; then
18     echo "Need hostname as argument."
19     false
20 fi
21 echo "${hostname}" > /etc/hostname
22 hostname "${hostname}"
23
24 final_ip="127.0.1.1"
25 for ip in $(hostname -I); do
26     range_1=$(echo "${ip}" | cut -d "." -f 1)
27     range_2=$(echo "${ip}" | cut -d "." -f 2)
28     if [ "${range_1}" -eq 127 ]; then
29         continue
30     elif [ "${range_1}" -eq 10 ]; then
31         continue
32     elif [ "${range_1}" -eq 172 ]; then
33         if [ "${range_2}" -ge 16 ] && [ "${range_2}" -le 31 ]; then
34             continue
35         fi
36     elif [ "${range_1}" -eq 192 ]; then
37         if [ "${range_2}" -eq 168 ]; then
38             continue
39         fi
40     fi
41     final_ip="${ip}"
42 done
43
44 echo "127.0.0.1 localhost.localdomain localhost" > /etc/hosts
45 echo "${final_ip} ${fqdn} ${hostname}" >> /etc/hosts