How to redirect STDOUT of sudo command on Linux and write to file as root?

A 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

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *