Monday 19 February 2018

linux - Adding a line into the hosts file, getting permission denied when using sudo - Mac


I'm trying to add a line into the hosts file on my Mac by executing a one line command on the terminal.


I thought this would be easy using sudo, but it returns "permission denied" when I try to add >> to the hosts file, but it works if I try replace > the hosts contents.


sudo echo test >> /etc/hosts
-bash: /etc/hosts: Permission denied
$

sudo echo test > /etc/hosts
Password:
$

OS is up to date.



Answer



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.


No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...