When sudo echo ‘test’ > /root/test gives permission denied

If you get a permission denied error when trying to redirect the output of a sudo command then the reason for this is normally because the superuser permissions only apply to the first part of the statement, e.g. the echo command. They do not carry through to the bash redirection.

paul@backups:~$ sudo echo 'test' >> /root/test
-bash: /root/test: Permission denied

One way to get round this is to use the tee command, as follows:

echo 'test' | sudo tee -a /root/test

Note that the -a switch means append to the file if it already exists.

7 thoughts on “When sudo echo ‘test’ > /root/test gives permission denied”

  1. This is great. Now I can control my fans through shell scripts, which wouldn’t work with Pablo’s suggestion.

    sudo echo 3 | sudo tee /proc/acpi/fan/FAN1/state

  2. Very useful! I was creating a document for a friend (LAMP install and configuration of Ubuntu) where after enabling php for user directories he could create a test script for phpinfo. echo ” | sudo tee /var/www/phpinfo.php. Your solution worked!

Leave a Reply

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