Adding a line into the hosts file, getting permission denied when using sudo - Mac
That's because echo
is being run as root, but the shell is the one actually performing the redirection. You need to spawn a new shell for this to work:
sudo -- sh -c "echo test >> /etc/hosts"
Edit: I haven't seen the fact that the >
redirect works; I can't explain that.
Rather then running echo through a redirect which will be run as your current user, not root as echo is being run in your example, use tee as Steve Buzonas suggests
echo 'test' | sudo tee -a /etc/hosts
The sudo is now applied to the tee command. The '-a' appends to the file
This will also output tee to standard output. If you don't want to see 'test' in your terminal also add: > /dev/null
to the end of that line.