Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check IPs if they exist in /etc/hosts

I am trying to create a .sh script that checks if some IP/Domain like "teamspeak.com" exists in /etc/hosts and if it does not then I want to add something to the hosts file.

Right now I am trying this with:

if ! grep -q "teamspeak.com == teamspeak.com" /etc/hosts; then
    echo "Exists"
else
    echo "Add to etc host ting here" >> /etc/hosts;

fi
like image 740
JonathanNet Avatar asked Mar 16 '15 16:03

JonathanNet


People also ask

Does nslookup check etc hosts?

The nslookup utility in Red Hat, SuSE and other Linux operating systems can only resolve hostnames or IP addresses that are in a DNS database. nslookup is not coded to consult the /etc/nsswitch. conf file, and it is not able to resolve hostnames or addresses that are in the local /etc/hosts file.

How do I view etc hosts?

In Windows 10 the hosts file is located at c:\Windows\System32\Drivers\etc\hosts. Right click on Notepad in your start menu and select “Run as Administrator”. This is crucial to ensure you can make the required changes to the file. Now click File > Open and browse to : c:\Windows\System32\Drivers\etc\hosts.

What does ETC hosts contain?

The /etc/hosts file contains the Internet Protocol (IP) host names and addresses for the local host and other hosts in the Internet network. This file is used to resolve a name into an address (that is, to translate a host name into its Internet address).


1 Answers

grep -q 

exits with 0 if any match is found, otherwise it exits with 1 so you need to remove ! and == comparison:

if grep -q "teamspeak.com" /etc/hosts; then
    echo "Exists"
else
    echo "Add to etc host ting here" >> /etc/hosts;
fi

Note that it is not word based search so it finds myteamspeak.com or teamspeak.com.us too. To get the whole host name you need to use cut command with delimiters.

To add a new host use:

echo "127.0.0.1 teamspeak.com" >> /etc/hosts
like image 184
AlecTMH Avatar answered Oct 04 '22 22:10

AlecTMH