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