2

I'm trying to append a line to the hosts file on a mac. The command I'm using is:

sudo echo "192.168.99.100 test" >> /private/etc/hosts

This method does work on windows & linux but on Mac I do not have the permissions to run this even when running it in sudo mode.

Can anybody tell me what I'm doing wrong and how I can fix this?

StefanJanssen

StefanJanssen
  • 446
  • 1
  • 7
  • 18
  • Possible duplicate of [How do I use sudo to redirect output to a location I don't have permission to write to?](http://stackoverflow.com/questions/82256/how-do-i-use-sudo-to-redirect-output-to-a-location-i-dont-have-permission-to-wr) – Neil May 03 '16 at 10:25

1 Answers1

4

Try echo '192.168.99.100 test' | sudo tee -a /private/etc/hosts.

>> is syntax of the shell itself, which is running as your user. sudo echo "192.168.99.100 test" >> /private/etc/hosts runs echo "192.168.99.100 test" as root and the >> "pipe to file" is run as your user.

tee is an ordinary command you can run as root with sudo which outputs to both stdout and a file, so echo 'line' | sudo tee -a file will do what you want. tee -a will append to the file instead of overwriting it.

Candy Gumdrop
  • 2,745
  • 1
  • 14
  • 16
  • @trojanfoe What looks like rubbish? – Candy Gumdrop May 03 '16 at 10:39
  • @trojanfoe It's not, the redirection is run in the current shell which does not have sudo priveleges. – 123 May 03 '16 at 10:42
  • `sudo` is just an ordinary command which takes in input via command line arguments. `>>` is interpreted by the shell instead of being added as an argument to the command. That's why `echo 'hello' >> file` doesn't display `hello >> file` and instead writes `hello` to the file `file`. – Candy Gumdrop May 03 '16 at 10:44