Sudo Echo “To” > File: Permission Denied [SOLVED]

If you try to echo something to a file that you don’t have permission to write to, you will receive the “permission denied” error.

But, what might seem surprising, if you try to repeat the same echo command with sudo, you will still receive the same “permission denied” error.

The construction sudo echo 'something' > file doesn’t work, because the redirection i.e. > or >>, is executed not by the sudo echo, but by the current user’s shell (that is not running as root).

Sudo Echo to File

There are several ways of how to solve the “permission denied” error when using sudo with redirection and the first of them is by using the tee command.

Warning: The tee command without the -a, --append flag will overwrite the file!

Instead of redirecting ‘something‘ to a truncated file like this:

$ sudo echo 'something' > file.txt

Do it like this:

$ echo 'something' | sudo tee file.txt

And instead of redirecting ‘something‘ and appending it to a file like this:

$ sudo echo 'something' >> file.txt

Do the following:

$ echo 'something' | sudo tee -a file.txt
- or -
$ echo 'something' | sudo tee --append file.txt

As an alternative to the tee command you can simply make sure the redirection happens in a shell with the right permissions:

$ sudo bash -c "echo 'something' > file.txt"
$ sudo bash -c "echo 'something' >> file.txt"
Was it useful? Share this post with the world!

5 Replies to “Sudo Echo “To” > File: Permission Denied [SOLVED]”

  1. Thank you for this, I tested it, and worked all fin. But the simplest solution I found out was to just use sudo -s avoiding the validation all togeter. This way you don’t have to change anything and you can run your commands as is.

  2. Clear and helpfull!

    Thanks

  3. Very clear explanation, thanks

  4. Tried it, and I’m glad to report it worked!

Leave a Reply