Why Does Sudo Echo Fail with Permission Denied?
- Adam Douglas
It makes sense that if you try to echo something to a file, and you receive permission denied, it’s because the user is not allowed to do so. What seems to be puzzling to some, is if you try to echo something again with the sudo command, and still receive “permission denied”. Let’s solve this puzzling behaviour, so it all becomes clear, why the command would fail with sudo.
The command fails even though sudo is being used to elevate the user’s permissions.
$ sudo echo 'Hello World!` > /home/test.txt
-bash: test.txt: Permission denied
The reason this command fails with the use of sudo is because the redirection (e.g. >, >>, etc.) is not executed with elevated user permissions (e.g. root). Instead, the redirection is actually executed by the current user’s shell, thus this is why an error of “permission denied” is returned.
There are several ways in which to overcome this problem.
$ echo 'Hello World!' | sudo tee /home/test.txt
The tee command without -a or --append parameter will overwrite the file if it already exists.
The reason this works is that the command
echo 'Hello World!' | sudo is executed under the user’s shell permission.
The pipe character (|) will then pass on the standard output to the tee command allowing the file to be written. The
tee works by reading from standard input, write to standard output and can also do the same with files.
By using the Bash command with the parameter “-c” the entire command will be executed with sudo that provides the elevated permissions.
$ sudo bash -c "echo 'Hello World!' > test.txt"
This is post 51 of 100, and is round 2 of the 100 Days To Offload challenge.