check IPs if they exist in /etc/hosts
Asked Answered
V

1

8

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
Vicariate answered 16/3, 2015 at 16:49 Comment(4)
you know.. questions should have questions..Worldwide
Sorry,but, what is meant by IPS here? Couldn't get what you want!Skite
i think he is referring ips to unresolved domain names..Worldwide
Yes It should look for ip/domainsVicariate
S
13
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
Sprung answered 16/3, 2015 at 17:3 Comment(3)
Great job providing a relevant scripting answer, when the intent of the question probably was off-topic (I think he's asking what should go in the "Add to etc" placeholder... which has nothing to do with programming)Disproportionation
nice seams to work so far but how do I add this if thay not exits nopaste.linux-dev.org/?450741 ? allso with tabs ?Vicariate
This fails if there is a commented entry with the term(teamspeak.com) of grep in /etc/hosts file.Mazonson

© 2022 - 2024 — McMap. All rights reserved.