Why does redirecting "sudo echo" stdout to a file not give root ownership?

0

I'm pretty new to using Linux heavily, and I'm trying to learn more about file ownership and permissions. One thing that I stumbled on just now was exactly what the title says, running:

weee@my-server:~$ sudo echo "hello" > some-file.txt
weee@my-server:~$ ls -lh
total 4.0K
-rw-rw-r-- 1 weee weee 6 Dec  5 21:21 some-file.txt

The file is owned by me, whereas touch works like one would expect:

weee@my-server:~$ sudo touch other-file.txt
weee@my-server:~$ ls -lh
total 4.0K
-rw-r--r-- 1 root    root    0 Dec  5 21:22 other-file.txt

How can I force the file to be created by root? Do I simply have to create the file in my homedir, then sudo chown root... and sudo mv ... move it to /var where I need it to be? I was hoping there'd be a single step to accomplish this.

orokusaki

Posted 2012-12-06T02:24:48.890

Reputation: 1 044

Ah, figured it out (see answer). Linux is so awesome. – orokusaki – 2012-12-06T02:39:14.697

Answers

3

The command:

sudo [some command] > [some file]

simply runs the command as root, but then redirects the output as the current user. In order to accomplish what you're looking for, try:

sudo bash -c "[some command] > [some file]"

orokusaki

Posted 2012-12-06T02:24:48.890

Reputation: 1 044

0

if you need a file's ownership to be root, you can also switch users to root. (If possible and appropriate):

su root

Mike Lyons

Posted 2012-12-06T02:24:48.890

Reputation: 227