0

The following command works as expected:

# Add/create /tmp/hosts with the string content inside EOFs
$ cat >> /tmp/hosts <<EOF
127.0.0.0 example.com
127.0.0.0 foo.example.com
EOF

However, the following command yields an error even when the sudo'd account has a permission to write to /etc/hosts.

$ sudo cat >> /etc/hosts <<EOF
127.0.0.0 example.com
127.0.0.0 foo.example.com
EOF

-bash: /etc/hosts: Permission denied

Why? And how can one achieve exactly what the above command intends to?

OTZ
  • 3,003
  • 4
  • 29
  • 41
  • 5
    use sudo command before cat,go here for more http://superuser.com/questions/538760/adding-a-line-into-the-hosts-file-getting-permission-denied-when-using-sudo-m – insomniac Dec 07 '13 at 09:30

1 Answers1

3

Thanks to the provided link by: @insomniac

Following should work:

sudo -- bash -c 'cat << EOF >> /etc/hosts
127.0.0.0 example.com
127.0.0.0 foo.example.com
EOF'

Otherwise redirection is handled by current user process not by sudo.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Awesome. Thank you and @insomniac for the quick answer. – OTZ Dec 07 '13 at 09:39
  • so you added an __invaluable answer__ given the reference to the other question. Sweet. – devnull Dec 07 '13 at 09:40
  • 1
    @devnull: Sorry you feel upset, I believe insomniac should have posted the answer not a comment. – anubhava Dec 07 '13 at 09:58
  • 1
    @devnull I'm with anubhava on this. Do look back on my original question where I specifically ask "how can one achieve exactly what the above command intends to?" The link insomniac provided does nothing do answer it. – OTZ Dec 07 '13 at 10:18
  • @anubhava (1) That's not quite how SO works. (2) I'd doubt if you would understand that given how your answers often change (& are _inspired_ by) other answers in a given post. – devnull Dec 10 '13 at 18:19
  • @devnull: I have also experienced numerous instances when my answers/comments prompted other posters to change their answers but have always taken that in right spirit. OP's comment is here as well. Though I really don't want make this as a point of unnecessary arguments as I consider you (and few others) good & knowledgeable companion on this platform. – anubhava Dec 10 '13 at 18:31