Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

echo

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?

like image 531
Spanky Avatar asked Nov 30 '22 11:11

Spanky


1 Answers

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'
like image 64
Keith Thompson Avatar answered Dec 04 '22 06:12

Keith Thompson