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"

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

Leave a Reply