linux - 使用 shell 脚本将行附加到/etc/hosts 文件

我有一个新的 Ubuntu 12.04 VPS。我正在尝试编写一个安装脚本来完成整个 LAMP 安装。我遇到问题的地方是在 /etc/hosts 文件中添加一行。我当前的主机文件如下所示:

127.0.0.1       localhost Venus

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

我希望它看起来像这样:

127.0.0.1       localhost Venus
192.241.xx.xx  venus.example.com venus

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

我已经使用 append (\a) 命令尝试了各种 sed 命令。出于某种原因,Ubuntu 要么只是在终端中回显 hosts 文件的内容,要么什么都不做。如何使用 bash 脚本将第二行正确地注入(inject)文件中?

最佳答案

确保使用 sed-i 选项。

-i[SUFFIX], --in-place[=SUFFIX]
  edit files in place (makes backup if extension supplied)

sed -i "2i192.241.xx.xx  venus.example.com venus" /etc/hosts

否则,

echo "192.241.xx.xx  venus.example.com venus" >> /etc/hosts

将在文件末尾追加该行,这可以按您的预期工作。

https://stackoverflow.com/questions/19339248/

相关文章:

linux - 我可以阅读 Linux 内核的哪些部分以获得乐趣?

linux - 双斜杠//in `cd//` 在 Linux 中是什么意思?

c - Linux 中的 bluetooth/bluetooth.h 位于何处?

linux - tr 命令 - 如何将字符串 "\n"替换为实际的换行符 (\n)

c - 枚举中这些#define 的目的是什么?

linux - 解释导出 LANG、LC_CTYPE 和 LC_ALL 的效果

linux - 进程可以拥有的每个不同 UID 的目的是什么?

linux - 使用命令或 bash 脚本清理环境?

linux - 从 rpm 包中提取规范文件

c - bzero() & bcopy() 与 memset() & memcpy()