I have a new Ubuntu 12.04 VPS. I am trying to write a setup script that completes an entire LAMP installation. Where I am having trouble is appending a line to the /etc/hosts
file. My current hosts file looks like this:
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
I would like it to look like this:
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
I have tried a variety of sed
commands using the append (\a
) command. For some reason Ubuntu either just echoes the contents of the hosts
file in terminal or does nothing at all. How would I properly inject the second line into the file with a bash script?
The most used newline character If you don't want to use echo repeatedly to create new lines in your shell script, then you can use the \n character. The \n is a newline character for Unix-based systems; it helps to push the commands that come after it onto a new line. An example is below.
Make sure to use the -i
option of sed
.
-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
Otherwise,
echo "192.241.xx.xx venus.example.com venus" >> /etc/hosts
would append the line at the end of the file, which could work as you expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With