我有一个新的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或者只是在terminal中回应hosts
文件的内容,或者什么也不做。 我将如何正确地注入第二行到bash脚本的文件?
确保使用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
会在文件末尾追加行,这可以像你期望的那样工作。
如果你想以编程方式插入/更新使用bash主机条目,这里是我写的脚本来做到这一点:
#!/bin/bash # insert/update hosts entry ip_address="192.168.xx" host_name="my.hostname.example.com" # find existing instances in the host file and save the line numbers matches_in_hosts="$(grep -n $host_name /etc/hosts | cut -f1 -d:)" host_entry="${ip_address} ${host_name}" echo "Please enter your password if requested." if [ ! -z "$matches_in_hosts" ] then echo "Updating existing hosts entry." # iterate over the line numbers on which matches were found while read -r line_number; do # replace the text of each line with the desired host entry sudo sed -i '' "${line_number}s/.*/${host_entry} /" /etc/hosts done <<< "$matches_in_hosts" else echo "Adding new hosts entry." echo "$host_entry" | sudo tee -a /etc/hosts > /dev/null fi
该脚本旨在与OS X一起使用,但也可以在Linux上进行小的调整。
如果你在mac或者你需要sudo权限来试试这个:
sudo -- sh -c -e "echo '192.34.0.03 subdomain.domain.com' >> /etc/hosts";
它仍然会要求你输入密码。
echo "127.0.0.1 localhost `hostname`">./temp_hosts echo "192.241.xx.xx venus.example.com">>./temp_hosts cat /etc/hosts |tail -n +2 >>./temp_hosts cat ./temp_hosts > /etc/hosts rm ./temp_file
我应该指出, sed
( 流编辑器)实际上不是用来编辑文件的,尽管它可以用来做到这一点。 ( 标准sed没有内置的机制来写入除标准输出以外的内容。)更合适的工具将被ed
。
下面的编辑脚本说:“找到包含(诚然马虎)正则表达式/127.0.0.1/行,并追加在下一行。” (孤独的时期告诉编辑停止追加。)
ed /etc/hosts <<-'EOF' /127.0.0.1/a 192.241.xx.xx venus.example.com . wq EOF
也就是说,你可以非常简单地将这行添加到/ etc / hosts文件的末尾 :
echo '192.241.xx.xx venus.example.com' >> /etc/hosts
你可以使用sed,比如:
sed'/ Venus / a \
venus.example.com venus'/ etc / hosts