Confused Development

I develop software and I often get confused in the process. I usually find the answers after a while, but a month later I can't remember them. So from now on, I will write them down here.

Thursday, October 08, 2009

Linux/Unix: Redirecting Output Using ">" with sudo

Problem: In Linux/Unix, you want to redirect output of something to a file with > you don't have write permissions for:

local$ ls -la > test.txt
-bash: test.txt: Permission denied

You think "I can solve this by using sudo"! But, alas:

local$ sudo ls -la > test.txt
-bash: test.txt: Permission denied

The shell won't even ask for your password. This indicates to me that somehow sudo only applies to the ls command here. What seems to happen is that first, the shell tries to open the file and only then runs the ls command to feed it with input. But since you don't have write permissions for this file, the execution of the whole expression is stopped. The way to solve this, as I found out in this blog post, is to run bash (or any other shell) as sudo and then give it the entire expression as a parameter:

local$ sudo bash -c "ls -la > test.txt"
Password:
local$ more test.txt
total 16
drwxr-xr-x  18 root  wheel   612 Oct  8 16:23 .
drwxr-xr-x@ 13 root  wheel   442 Dec  6  2007 ..
drwxr-xr-x@ 13 knud  staff   442 Sep  8 11:45 arc
drwxr-xr-x  61 root  wheel  2074 Apr 17 12:30 bin
drwxr-xr-x  14 root  wheel   476 Dec  4  2007 gwTeX
drwxr-xr-x  33 root  wheel  1122 Feb 17  2009 include
drwxr-xr-x  56 root  wheel  1904 Feb 17  2009 lib
-rw-r--r--   1 root  wheel     0 Oct  8 16:23 test.txt

Note that test.txt is already in the this list, proving that the file was created before the ls command was run!

Labels: , ,

1 Comments:

At 8:43 pm, Blogger Aristotle said...

The shell will pass its root permissions down to ls, though. You don’t necessarily want that.

Here’s a different solution that restricts the scope of root permissions to what they are needed for:

ls -la | sudo sed -n ‘w test.txt’

This indicates to me that somehow sudo only applies to the ls command here.

Of course. After all, sudo is just a program like any other. It just so happens that sudo happens to be setuid root, and it so happens that it interprets the arguments passed to it as a command to run in turn, which effectively results in that command running with root permissions. So sudo is not a special shell keyword or anything like that – whereas the redirection operators are interpreted by the shell.

 

Post a Comment

<< Home