sudo and >>: permission denied
I ran into this interesting problem today. I have the following directory:
drwxr-xr-x 2 mcd mcd 168 2008-06-25 12:05 .
drwxr-xr-x 23 mcd mcd 1360 2008-06-25 12:04 ..
-rw-r--r-- 1 root root 15883 2008-06-25 12:05 dmesg.txt
-rw-r--r-- 1 root root 655133 2008-06-25 12:05 messages.txt
-rw-r--r-- 1 root root 0 2008-06-25 12:05 out
-rw-r--r-- 1 mcd mcd 2114 2008-06-25 12:05 update.txt
These are test files I just created. Now, I want to cat the contents of the text files and append them to out:
$ sudo cat *.txt >> out
Only I get permission denied:
-bash: out: Permission denied
It's the same if I try these:
$ sudo cat *.txt > out
$ sudo cat *.txt | sudo >> out
But if I su to root, and then just run cat *.txt >> out it works just fine. So it seems like the change of identity does not "propagate" past the >>. Sudo's man page doesn't help me understand this any better. Does anyone have any insight into what's actually going on here?
Actually the man page DOES say you have to run it in a subshell to allow redirection to work (or gives an example that tells you that):
So to do what you want you just need to modify your command line:
sudo sh -c "cat *.txt >> out"
sudo cat *.txt >> out
The shell you're using interprets this as.
sudo cat *.txt # Elevates privs
Then take the output and put it into file out.
The first part is run as root 'cat *.txt' then your shell, running as you and outside of the sudo escalated privs, tries to open a file 'out' and put the output in it.
Thus the permission denied.
Hopefully this made a tiny bit more sense to you.
The subshell example above in this thread should fix it as well.
|All times are GMT -5. The time now is 06:52 PM.|