I have a file named foo whose permissions are -rwxr-x--- root and I'm neither the user (root) nor in the group. I have another file named bar, which I want to append to foo. I've tried

sudo cat bar >> foo

but this fails with foo: Permission denied.

  • Downvoters, care to explain please? – dimid Dec 20 '17 at 12:02
  • Yes, downvoters why???? – George Udosen Dec 20 '17 at 12:03
cat bar | sudo tee -a foo > /dev/null

man tee:

-a, --append

append to the given FILEs, do not overwrite

Here, we use tee as sudo in order to append to foo, and dump (to /dev/null) the other effect of tee: duplicating the input to the stdout.

  • Great, thanks! Could you explain why the original sudo fails? – dimid Dec 20 '17 at 12:01
  • 1
    It fails because sudo applies only to cat. – muclux Dec 20 '17 at 12:02
  • can also do sudo tee -a /foo <bar >/dev/null – randominstanceOfLivingThing Dec 20 '17 at 13:35

Another way to achieve that would be this:

sudo bash -c "cat bar >> foo"

Not the answer you're looking for? Browse other questions tagged or ask your own question.