Saturday, September 27, 2008

Redirecting output to a file with sudo

Sometimes, we may need to redirect output to a file owned by root ( or another user ) to which we have permission via sudo.

[alanhaggai@archer ~]$ sudo touch test
[alanhaggai@archer ~]$ stat test
  File: `test'
  Size: 0               Blocks: 0          IO Block: 4096   regular empty file
Device: fe00h/65024d    Inode: 281248      Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2008-09-27 17:08:29.000000000 +0530
Modify: 2008-09-27 17:24:03.000000000 +0530
Change: 2008-09-27 17:24:03.000000000 +0530
[alanhaggai@archer ~]$ sudo echo 'hello' > test
bash: test: Permission denied

sudo executes echo 'hello' as root. Then bash tries to write the output to the file named test as the user alanhaggai. man sudo states:

sudo [-bEHPS] [-p prompt] [-u username⎪#uid] [VAR=value] {-i ⎪ -s ⎪ command}

To circumvent this problem, we use:

[alanhaggai@archer ~]$ sudo bash -c 'echo "hello" > test' [alanhaggai@archer ~]$ cat test hello

0 comments: