4

Why when I run I get the error:

$ sudo echo "127.0.0.1 db-local.internal" >> /etc/hosts
bash: /etc/hosts: Permission denied

But when I do sudo su I can edit this file without any problem.

UPD
Because question is closed I add answer here:

sudo bash -c "echo 'some string' >> test.txt"

Link: https://serverfault.com/a/68544/307225

Eugen Konkov
  • 194
  • 1
  • 2
  • 13
  • then you're not in sudoers – Sum1sAdmin Apr 13 '16 at 09:47
  • make sure you are in /etc/sudoers and allowed to do more than just 'sudo su' – Ialokin Apr 13 '16 at 09:48
  • you can also try 'sudo -user=root echo "127.0.0.1 db-local.internal" >> /etc/hosts' – Ialokin Apr 13 '16 at 09:49
  • @Rob-d There is no indication that the user does not have `sudo` rights. The problem here occurs because the shell redirect happens in the user's security context, not sudo context. The user themselves doesn't have rights to edit the file /etc/hosts. – Cosmic Ossifrage Apr 13 '16 at 11:05

1 Answers1

0

Try

sudo 'echo "127.0.0.1 db-local.internal" >> /etc/hosts'

The way you written it, you will try to append the output of sudo to /etc/hosts before the sudo becomes active.

Sven
  • 98,649
  • 14
  • 180
  • 226
  • 3
    sudo: echo "127.0.0.1 db-local.internal" >> /etc/hosts: command not found – Eugen Konkov Apr 13 '16 at 10:30
  • 1
    Another approach might be to use [`tee`](https://en.wikipedia.org/wiki/Tee_%28command%29). i.e. `echo "127.0.0.1 db-local.internal" | sudo tee -a /etc/hosts`. This forces the append operation to run in the context of a UID `0` user. See [this answer](http://serverfault.com/a/68557/131019) in the linked duplicate question, which also describes this method. – Cosmic Ossifrage Apr 13 '16 at 11:06
  • I have found answer at different topic – Eugen Konkov Apr 13 '16 at 11:08
  • 1
    @EugenKonkov was that other solution: `sudo /bin/bash -c 'echo hello >> /etc/hosts`? – a.t. Mar 29 '21 at 14:58
  • 1
    @a.t.: Answer is here: https://serverfault.com/a/68544/307225 – Eugen Konkov Apr 15 '21 at 11:55