Patch without changing owner and group

chownpatch

I've got a file owned by a non-root user:

# ls -l example.php
-rw------- 1 foo bar ... example.php

I just applied a patch with a command like

patch -p0 <<-EOF
--- .../example.php.orig 2012-06-20 15:07:13.000000000 +0200
+++ .../example.php  2012-06-20 15:43:05.000000000 +0200
...
EOF

as root and the target file user and group were both changed to root. I couldn't find any reference to this in the man pages.

Is there a way to leave the file ownership as before without using su, sudo, or chown?

  • su seems unable to specify a group.
  • sudo -u foo patch ... runs fine, but sets the wrong group.
  • sudo -u foo -g bar patch ... returns Sorry, user root is not allowed to execute '/usr/bin/patch' as foo:bar on hostname. This might be because user foo is not a member of group bar.
  • chown would mean having to store the permissions before running patch, adding another two lines of code.

Best Answer

patch creates new file, that's why it holds effective user credentials.

A workaround: use patch -o to have temporary file created, then simply cat tmp file to original file.

Related Question