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.

2 1 vote
Article Rating
Subscribe
Notify of
guest

6 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Smita
Smita
2 years ago

I have tried this code but getting an error as follows
sed: couldn’t open temporary file /etc/sedugqFPg: Permission denied

Mohit
Mohit
5 years ago

pretty easy one

Saket Jain
Admin
5 years ago

Hope you are able to execute the script now….

vaibhav gupta
vaibhav gupta
Reply to  Saket Jain
5 years ago

Thank you .Nice article

Brent
Brent
5 years ago

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

Saket Jain
Saket Jain
Reply to  Brent
5 years ago

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.