Sometimes you want to redirect the output of a command into a file that you don't own.

$ ls -al /tmp/root_owns_this
-rw-r----- 1 root wheel 10 Aug 21 09:06 /tmp/root_owns_this
$ echo "test" > /tmp/root_owns_this
-bash: /tmp/root_owns_this: Permission denied

Your first instinct may be to simply use sudo:

$ sudo echo "test" > /tmp/root_owns_this
-bash: /tmp/root_owns_this: Permission denied

Same error.  Why? Because sudo is only elevating the privileges of the echo command.  The redirect still belongs to your shell.

I'm aware of two options to get around this, although I'm sure there are others.

$ echo "test" | sudo tee /tmp/root_owns_this # Create/overwrite the file
$ echo "test" | sudo tee -a /tmp/root_owns_this # Append to the file


$ sudo bash -c "echo \"test\" > /tmp/root_owns_this" # Create/overwrite the file
$ sudo bash -c "echo \"test\" >> /tmp/root_owns_this # Append to the file

The downside to the first option is that tee is going to echo anything piped to it to STDOUT.  You can work around this by redirecting STDOUT to /dev/null.   The potential downside to the second option is properly escaping the commands within the call to bash.