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

27,606

Solution 1

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.

Solution 2

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.

Solution 3

Works also well from a script:

sudo /bin/sh -c 'echo "127.0.0.1 mydomain" >> /etc/hosts'

Solution 4

To ensure that a new line was created first, I used this:

sudo -- sh -c "echo  \ \ >> /etc/hosts";sudo -- sh -c "echo 127.0.0.1  testdomain.com >> /etc/hosts"
Share:
27,606

Related videos on Youtube

Mint
Author by

Mint

Updated on September 18, 2022

Comments

  • Mint
    Mint almost 2 years

    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.

    • MrSmith42
      MrSmith42 over 11 years
      simply use a text editor (started with sudo) to modify your /etc/hosts
    • Mint
      Mint over 11 years
      I want to make a script that will help automate this, so a text editor wouldn't help in this case.
  • Steve Buzonas
    Steve Buzonas over 10 years
    I feel it's worth noting the utility tee because allowing a subshell execution from sudo is and should be blocked in most production environments for security reasons.
  • Alien Life Form
    Alien Life Form over 3 years
    I like this because it matches our crontab scripting style.