HowTo Redirect stdout When Using sudo

problem: you’d like to run a command as root, using sudo, and redirect the output to a file. this won’t work:

sudo echo hello > /hello

why? sudo runs echo as root, but the current shell takes over and tries to do the redirection without root privileges.

solution: spawn a shell and feed it the command:

sudo sh -c "echo hello > /hello"

updated: Tue Apr 6 08:01:43 PDT 2010