0

I have a file called "s" owned by root. I want to replace its content with something else using sudo but it fails: "sudo ls -l > s" gives permission denied. However, when I do the same after sudo su, everything works.

I'd like to learn why my sudo command failed? I suspect only ls was running with root privileges and not the ">" operation so it failed. If that's the case how do I sudo that?

Background: I want to use this in a script so I can't use sudo su inside that.

For reference, here's what I tried:

xropi@xropi-VirtualBox2:~/w$ ls -l
total 4
-rw-r--r-- 1 root root 18 Dec 25 01:33 s

xropi@xropi-VirtualBox2:~/w$ cat s asdf sadf dsf sdf

xropi@xropi-VirtualBox2:~/w$ sudo ls -l > s bash: s: Permission denied

But when I use sudo su, everything works:

xropi@xropi-VirtualBox2:~/w$ sudo su

root@xropi-VirtualBox2:/home/xropi/w# ls -l > s

root@xropi-VirtualBox2:/home/xropi/w# cat s total 0 -rw-r--r-- 1 root root 0 Dez 25 01:34 s

root@xropi-VirtualBox2:/home/xropi/w#

xropi
  • 93

1 Answers1

4

The output redirect is being evaluated by your shell, not the process run by sudo. The shell interprets things like redirects (>) before evaluating the commands, so sudo doesn’t know you are redirecting to a file, the shell just attaches the stdout filehandle of the command to the file instead of the tty.

Since your shell is running under your account, it is trying to write to the file as your account, which is why it fails.

If you want to write the file as root, use something like tee, as in this example:

ls -l | sudo tee s

This way, instead of a redirect, the output of ls -l is piped to the tee command, and it is running as root under sudo.

If you absolutely want to use shell redirects, you’ll need to do something like:

sudo sh -c ‘ls -l > s’

Which just runs a shell (as root) doing basically what you run in your ‘sudo su’, just as a one liner.

jsbillings
  • 24,406