6

使用 sed 来切换 hosts 文件项

 3 years ago
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.
neoserver,ios ssh client

使用 sed 来切换 hosts 文件项

本文来自依云's Blog,转载请注明。

工作中经常会需要将一个域名映射到本地以调试,但是其余时间又需要让其正常解析。手工修改/etc/hosts文件烦耶!

于是有了以下脚本:

togglehost
#!/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 文件,而是显示相关行以查看状态。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK