1

I wanted to add to my hosts file easily using a one line command, but I get an unexpected result.

$ sudo sh -c 'echo -e "10.0.10.0\tserver.bananas.com\tserver" >> /etc/hosts'

$ cat /etc/hosts
-e 10.0.10.0        server.bananas.com        server

I'm using the -e switch on echo to enable the use of backslash escapes for the tabs, but the -e is being included in the redirected output.

How can I avoid this?

paradroid
  • 1,203

1 Answers1

3

I'm not exactly sure why echo is failing as per your question, but in general, I'd use printf instead. It's much more predictable in its output.

printf '%s\t%s\t%s\n' '10.0.10.0' 'server.bananas.com' 'server'

Explanation

  • %s\t%s\t%s\n: this part explains what the output format will be, i.e. a string, a tab, a string, a tab, a string, a newline.
  • The three strings are the following arguments supplied to printf.

Writing to root-owned files

Also, I'm not sure if you are aware, but instead of using the sudo sh -c construct, you could use sudo tee instead. i.e.

printf … | sudo tee -a /etc/hosts

I find this more convenient, especially when it avoids having to escape characters inside the external '.

Sparhawk
  • 19,941