How to redirect STDOUT of sudo command on Linux and write to file as root?
Posted on In QAA try like the following command failed
$ sudo echo "echo hello" > /usr/local/bin/hello
with an message
bash: /usr/local/bin/hello: Permission denied
It seems the writing to the file is executed under the non-root user.
How to redirect STDOUT of sudo command on Linux and write the content to the file (/usr/local/bin/hello here) as root?
You can make sudo invoke bash which executes your command:
sudo bash -c 'echo "echo hello" > /usr/local/bin/hello'
Another way is to use tee
to write to file instead of STDOUT redirection:
sudo echo "echo helo" | sudo tee /usr/local/bin/hello >/dev/null