Search code examples
bashechosudo

Why can't I echo contents into a new file as sudo?


I came across this weird problem just now and I can't seem to get to the bottom of it. I'm trying to add a config file to /etc/sudoers.d/ but get permission denied. In the example below, the file "tweedle" doesn't exist and:

drwxr-xr-x  2 root root   4.0K Jan  2 18:27 sudoers.d/

So here's the command:

$ sudo echo "tweedle ALL=(ALL) ALL" > /etc/sudoers.d/tweedle
-bash: /etc/sudoers.d/tweedle: Permission denied

It doesn't even work when I break it into two commands:

$ sudo touch /etc/sudoers.d/tweedle
$ sudo echo "poodle" > /etc/sudoers.d/tweedle

When I tested it locally, same problem:

$ cd ~
$ mkdir -m 755 tweedle
$ sudo chown root:root tweedle
$ sudo echo "battle" > ~/tweedle/beetle
-bash: /home/spanky/tweedle/beetle: Permission denied
$ sudo touch tweedle/beetle
$ sudo echo "battle" > tweedle/beetle
-bash: tweedle/beetle: Permission denied

Without sudo, all is well:

$ cd ~
$ mkdir poodle
$ echo "noodle" > poodle/bottle
$ cat poodle/bottle
noodle

Thoughts?


Solution

  • The echo command is being run as root, but the redirection is done by your shell, so it's executed as the current user, not as root.

    The simplest solution is to invoke a root shell to run both the command and the redirection.

    Rather than:

    sudo echo line > file
    

    try this:

    sudo sh -c 'echo line > file'
    

    or

    sudo bash -c 'echo line > file'