sudo & redirect output

Like normally command append host sudo echo > /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