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?

asked Feb 5, 2015 by Eric Z Ma (44,280 points)

1 Answer

 
Best answer

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
answered Feb 9, 2015 by Eric Z Ma (44,280 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...