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

4
  • then you're not in sudoers
    – Sum1sAdmin
    Apr 13, 2016 at 9:47
  • make sure you are in /etc/sudoers and allowed to do more than just 'sudo su'
    – Ialokin
    Apr 13, 2016 at 9:48
  • you can also try 'sudo -user=root echo "127.0.0.1 db-local.internal" >> /etc/hosts'
    – Ialokin
    Apr 13, 2016 at 9: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. Apr 13, 2016 at 11:05

1 Answer 1

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.

5
  • 3
    sudo: echo "127.0.0.1 db-local.internal" >> /etc/hosts: command not found Apr 13, 2016 at 10:30
  • 1
    Another approach might be to use tee. 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 in the linked duplicate question, which also describes this method. Apr 13, 2016 at 11:06
  • I have found answer at different topic Apr 13, 2016 at 11:08
  • 1
    @EugenKonkov was that other solution: sudo /bin/bash -c 'echo hello >> /etc/hosts?
    – a.t.
    Mar 29, 2021 at 14:58
  • 1
    @a.t.: Answer is here: serverfault.com/a/68544/307225 Apr 15, 2021 at 11:55

Not the answer you're looking for? Browse other questions tagged .