Check IP addresses if they exist in / etc / hosts

I am trying to create a .sh script that checks if any IP / Domain exists, for example "teamspeak.com" in / etc / hosts, and if not, I want to add something to the hosts file.

Now I'm trying to do 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 
+5
source share
1 answer
 grep -q 

exits from 0 if any match is found, otherwise it exits from 1, so you need to delete! 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 this is not a word-based search, so it finds myteamspeak.com or teamspeak.com.us. To get the whole host name, you need to use the cut command with delimiters.

To add a new host usage:

 echo "127.0.0.1 teamspeak.com" >> /etc/hosts 
+8
source

Source: https://habr.com/ru/post/1215466/


All Articles