Why can the root user edit read-only files, but a regular user with sudo access can’t

file-permissionssudounix

If you try to append to a file with no write permissions (say, the /etc/sudoers file which is is owned by root and has 0440 permissions), if you're the actual root user, this works. However, if you're another user using sudo, you get a permission denied error.

Why is this? It not because of the ownership of the file – it doesn't work with files owned by the normal user either. The real root user seems to have more permissions than are granted with sudo. What's the rationale for this? Is there a way to grant this permission to users using sudo?

Best Answer

Sounds like you're doing something like:

sudo echo "blah blah blah de blah" >> /etc/protected_file

This doesn't work because sudo applies to the echo command, which happily runs as root, but the redirect is part of your current shell, which isn't running as root.

Common solutions are:

sudo bash -c 'echo "blah blah blah de blah" >> /etc/protected_file'

and

echo "blah blah blah de blah" | sudo tee -a /etc/protected_file
Related Topic