#!/bin/bash CONFIG_FILE="/etc/sysconfig/network" function set_hostname() { NAME=$1 [ -n "$NAME" ] || exit 0 sed -i '/^HOSTNAME=.*$/d' $CONFIG_FILE echo "HOSTNAME=$NAME" >> $CONFIG_FILE [[ $(awk -F= '/^VERSION_ID/ {gsub("\"","");print $2}' /etc/os-release) -ge 7 ]] && echo $NAME > /etc/hostname hostname $NAME } function get_dns_name() { first_ip=$(hostname -I | cut -d' ' -f1) text=$(host $first_ip) [ $? = 0 ] || exit 0 [[ $text == *"has no PTR record" ]] && exit 0 name=$(echo "$text" | awk '{print $(NF)}' | sed 's/\.$//') echo $name } if [ -n "$SET_HOSTNAME" ]; then set_hostname $(echo "$SET_HOSTNAME" | sed -e 's/[^-a-zA-Z0-9]/-/g' -e 's/^-*//g' -e 's/-*$//g') elif [ -n "$DNS_HOSTNAME" ]; then set_hostname $(get_dns_name) fi