linux - 检查IP是否存在于/etc/hosts

标签 linux bash sh synology

我正在尝试创建一个 .sh 脚本来检查/etc/hosts 中是否存在像“teamspeak.com”这样的 IP/域,如果不存在,那么我想向主机文件中添加一些内容。

现在我正在尝试:

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

fi

最佳答案

grep -q 

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

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

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

要添加新的主机使用:

echo "127.0.0.1 teamspeak.com" >> /etc/hosts

关于linux - 检查IP是否存在于/etc/hosts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29082466/

相关文章:

linux - 编写 .sh 代码

bash - 从一个文件中删除另一个文件中的行

sh - typeset -i2 var=2#0 在 bash/korn shell 中意味着什么?

c++ - 在 qt 的子目录项目中找不到 header

python - 仅在数据到达时管道

linux - rake -T ... noglob : command not found

bash ffmpeg 使用输入文件名作为输出视频文件名

php - 创建符号链接(symbolic link)以访问 linux 中的目录

linux awk 在多行上搜索和删除

bash - 当管道中发生错误时,如何使 bash 脚本最终失败