A script to add hostname and IP address to /etc/hosts file automatically.

In this post, we will check out small script which takes hostname and IP address from the user and add it to /etc/hosts file of our Linux system automatically.

So here goes the script:


#! /bin/bash
read -p "Enter host: " hostname
read -p "Enter IP address of the host: " ip
sed -i.bkp "$ a $hostname $ip" /etc/hosts

Seems interesting, lets see how to create the script file and how it operates:

First lets create the script:

[root@nglinux ~]# cat << EOF > edit_host.sh
> #! /bin/bash
> read -p "Enter host: " hostname
> read -p "Enter IP address of the host: " ip
> sed -i.bkp "$ a \$hostname \$ip" /etc/hosts
> EOF

Now lets make the script executable and run it to test the scenario.

[root@nglinux ~]# chmod +x edit_host.sh
[root@nglinux ~]# ./edit_host.sh 
Enter host: testhost1
Enter IP address of the host: 192.168.1.2

Now verify the contents of /etc/hosts file if it is edited successfully.

[root@nglinux ~]# tail /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4 nglinux
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
testhost1 192.168.1.2
[root@nglinux ~]# 

Just try it on your system and use the powerful sed command to perform such tasks and for automating them.

In case, you are not able to understand anything in the script, please do comment here, i will reply asap.

4
Leave a Reply

avatar
3 Comment threads
1 Thread replies
3 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
MohitSaket JainSaket JainBrent Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Mohit
Guest
Mohit

pretty easy one

Admin

Hope you are able to execute the script now….

Brent
Guest
Brent

When I tried the script it adds $hostname and $ip to the hosts file and doesn’t populate the hostname or ip.

Saket Jain
Guest
Saket Jain

Make Sure to use double quotes for the line :
sed -i.bkp “$ a $hostname $ip” /etc/hosts

Single quotes text is not processed by bash shell.