使用 sed 来切换 hosts 文件项
source link: https://blog.lilydjwg.me/2013/4/23/switch-hosts-entries-with-sed.39036.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
使用 sed 来切换 hosts 文件项
本文来自依云's Blog,转载请注明。
工作中经常会需要将一个域名映射到本地以调试,但是其余时间又需要让其正常解析。手工修改/etc/hosts
文件烦耶!
于是有了以下脚本:
#!/bin/bash
if
[[ $UID -
eq
0 ]];
then
sed
-i
'/^#127\.0\.0\.1\s\+example\.org/s/^#//;t;/^127\.0\.0\.1\s\+example\.org/s/^/#/'
\
/etc/hosts
systemctl restart dnsmasq
else
grep
-m1 -F
'example.org'
/etc/hosts
fi
使用 sed 是因为觉得没必要用 awk 这样复杂的东西,也正好更深入学习下 sed。此代码中用到了t
命令,它的语义是:
当当前行的上一个s
命令成功(至少替换一次)时,跳转到指定的标签。如果没有指定标签,则跳转到脚本尾部。上边的命令中,当example.org
域名这行被注释掉时,s
命令成功去掉其前的注释符,然后t
命令跳过后边加注释符的s
命令,到达脚本尾部。
标签使用冒号定义。以上命令使用标签时如下所示:
sed
-i
'/^#127\.0\.0\.1\s\+example\.org/s/^#//;te;/^127\.0\.0\.1\s\+example\.org/s/^/#/;:e'
\
/etc/hosts
当然,以上脚本还做了另一件事:当以普通用户身份执行时,不修改 hosts 文件,而是显示相关行以查看状态。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK