sudo
has problems, because it runs the command portion. After the redirect, sudo
is not effective anymore.
You can do this instead :
sudo bash -c "Your commands here > output_file"
carefully escaping the single or double quotes in the commands between quotes, in the nesting order you use them.
EDIT:
Explanation in a little deeper detail
When you run a script, you are actually creating a new sub-shell and your script runs in this sub-shell, but the output comes back to the current shell. Your new sub-shell where you run this script is run with sudo
privileges, so the scripts runs effectively as root. But when the run finishes, the shell exits and your sudo
goes * pooof *. The output comes back to your current, non-privileged shell. If you are expecting it to be written at a privileged location, it is not going to happen. Hence, running the new shell and the whole enchilada, inside a well defined bash
shell, makes it possible. Because, at this point, your command and output are all handled by the sudo
enabled shell, not half way as in the original case.
output_file
for writing before it even thinks about running sudo. But what really matters isn't the sequence of events, it's which process is responsible for what. – hobbs Mar 18 '16 at 19:53