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.
I have tried this code but getting an error as follows
sed: couldn’t open temporary file /etc/sedugqFPg: Permission denied
pretty easy one
Hope you are able to execute the script now….
Thank you .Nice article
When I tried the script it adds $hostname and $ip to the hosts file and doesn’t populate the hostname or ip.
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.