sudo & redirect output

Like normally command append host sudo echo 127.0.0.1 local.host > /etc/hosts, but we’ll get the Permission denied error message.

sudo testparm /etc/samba/smb.conf.master > /etc/samba/smb.conf
bash: /etc/samba/smb.conf: Permission denied

Then how to sudo and redirect output to a file?

One solution is to use sh -c option:

sudo sh -c "testparm /etc/samba/smb.conf.master > /etc/samba/smb.conf"

Or you could use a tee command like this:

testparm /etc/samba/smb.conf.master | sudo tee /etc/samba/smb.conf

More about tee usage

http://linux.101hacks.com/unix/tee-command-examples/