sudo doesn't affect redirections

In `sudo cmd > /root/file`, the shell — not sudo — opens the file, so the redirection still runs as your user.

Problem

Shell redirections (`>`, `>>`, `<`) are handled by the shell that parses the command line, *before* sudo runs. So `sudo echo data > /etc/file` opens `/etc/file` as the unprivileged user and writes — then fails with permission denied.

Bad

sudo echo "fixed" > /etc/secure.conf

Good

# Use sudo tee for the write half:
echo "fixed" | sudo tee /etc/secure.conf >/dev/null

# Or a subshell run under sudo:
sudo sh -c 'echo "fixed" > /etc/secure.conf'

Explanation

`sudo tee` is the idiomatic fix because it keeps the producing command unprivileged. The subshell form is necessary when multiple redirections must all run as root.

When It Matters

In sudo cmd > /root/file the redirection is performed by your shell, before sudo runs, and your shell does not have permission to create the file. The result is "Permission denied" from a line that appears to be running as root, which is one of the most confusing errors in shell scripting. The same applies to appends, to here-documents targeted at privileged files, and to tee-less pipelines that try to write into /etc or /var/lib.

Second Example

Note

Redirecting tee’s own output to /dev/null keeps the content from being echoed back to the terminal.

Exceptions

Reading from a privileged file has the same problem in reverse and the same fix (sudo cat). Redirection under sudo is fine when the target is a path you can already write, so the warning is only actionable when the destination requires elevation.

Faq

Q

Why does sudo sh -c work?

A

Because the redirection is inside the string that the elevated shell parses: sudo sh -c 'echo x > /root/f'. It works, but quoting user data into that string is risky, so tee is usually the better answer.

Q

Does this affect pipes as well?

A

The pipe itself is fine; each side runs with its own privileges. Only the redirection to a file is performed by the calling shell.

Q

How do I write a file owned by another user?

A

Write it with tee under sudo, then set ownership explicitly with sudo chown, rather than relying on the umask of whichever process created it.