Simple script to change the hostname permanently

Forum Forums General Tips and Tricks Simple script to change the hostname permanently

  • This topic has 0 replies, 1 voice, and was last updated Apr 22-10:04 pm by antixcat.
Viewing 1 post (of 1 total)
  • Author
    Posts
  • #105238
    Member
    antixcat

      Hello all,

      I found from this post:
      https://www.antixforum.com/forums/topic/changing-hostname-safely/#post-100814
      That there is a particular sequence of steps needed to succesfully change the hostname permanently. I have written a simple script to do this automatically for all who might find it useful:

      
      #!/bin/bash
      
      echo "WARNING: This script will force a logout on completion"
      
      read -p "Enter new hostname: " new_hostname
      
      # check if hostname is valid
      pattern='^[a-zA-Z0-9\-]+$'
      if ! [[ $new_hostname =~ $pattern ]]; then
      	echo "Not a valid hostname"
      	exit 1
      fi
      
      # get ip address from /etc/hosts
      ip=$(awk 'NR==1{print $1}' /etc/hosts)
      
      # edit /etc/hosts
      # ADD the line (at line 3):
      # ip-address	new_hostname
      # WITHOUT removing the old hostname (at line 2):
      # ip-address	current_hostname
      sudo sed -i "3i\\$ip	$new_hostname" /etc/hosts
      
      # REPLACE the only line in the file /etc/hostname
      echo $new_hostname | sudo tee /etc/hostname
      
      # again edit /etc/hosts and now REMOVE the old hostname (at line 2)
      sudo sed -i '2d' /etc/hosts
      
      # set new hostname
      sudo hostname -F /etc/hostname
      
      # logout
      pkill -KILL -u $USER
      
    Viewing 1 post (of 1 total)
    • You must be logged in to reply to this topic.