Search code examples
linuxfile-permissionspermission-denied

Why cannot root writes on a file that it owns and has write access to?


I need to write to a.txt. The file is owned by root with a read-write access. But still I cannot write over it with a sudo. Why?

% ls -l
total 8
-rw-r--r--  1 root  staff  6 Mar 24 00:30 a.txt

% sudo echo "hi" >> a.txt
zsh: permission denied: a.txt

Solution

  • The redirection happens before the commands are run, i.e. using the original user.

    Work-around:

    sudo sh -c 'echo "hi" >> a.txt'