Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|improve this question
    
Ah, figured it out (see answer). Linux is so awesome. –  orokusaki Dec 6 '12 at 2:39
add comment

2 Answers

up vote 3 down vote accepted

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]"
share|improve this answer
add comment

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

su root
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.