检查/ etc/hosts中是否存在IP

Jon*_*Net 6 linux bash sh synology

我正在尝试创建一个.sh脚本,检查/ etc/hosts中是否存在某些类似"teamspeak.com"的IP /域,如果没有,那么我想在hosts文件中添加一些东西.

现在我正在尝试这个:

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

fi
Run Code Online (Sandbox Code Playgroud)

Ale*_*TMH 10

grep -q 
Run Code Online (Sandbox Code Playgroud)

如果找到任何匹配则退出0,否则退出1,因此您需要删除!和==比较:

if grep -q "teamspeak.com" /etc/hosts; then
    echo "Exists"
else
    echo "Add to etc host ting here" >> /etc/hosts;
fi
Run Code Online (Sandbox Code Playgroud)

请注意,它不是基于单词的搜索,因此它也可以找到myteamspeak.com或teamspeak.com.us.要获取整个主机名,您需要使用带分隔符的cut命令.

要添加新主机,请使用:

echo "127.0.0.1 teamspeak.com" >> /etc/hosts
Run Code Online (Sandbox Code Playgroud)