Patch Command – Apply -p0 Patch from Any Working Directory

patch

I have a patch with absolute paths that I wish to use. i.e. the first few lines are as follows.

--- /usr/share/apps/plasma/packages/org.kde.pager/contents/ui/main.qml  2014-10-10 18:47:23.000000000 +1100
+++ /usr/share/apps/plasma/packages/org.kde.pager/contents/ui/main.qml.mod  2014-11-11 09:44:17.786200477 +1100

However, it fails unless I am in the root directory.

~$ cd
~$ sudo patch -i /tmp/fix_kde_icons.patch -p0
Ignoring potentially dangerous file name /usr/share/apps/plasma/packages/org.kde.pager/contents/ui/main.qml
Ignoring potentially dangerous file name /usr/share/apps/plasma/packages/org.kde.pager/contents/ui/main.qml.mod
can't find file to patch at input line 3
Perhaps you used the wrong -p or --strip option?
...
~$ cd /tmp
/tmp$ sudo patch -i /tmp/fix_kde_icons.patch -p0
... #same error as above
/tmp$ cd /usr
/usr$ sudo patch -i /tmp/fix_kde_icons.patch -p0
... #same error as above
/usr$ cd /
/$ sudo patch -i /tmp/fix_kde_icons.patch -p0
patching file /usr/share/apps/plasma/packages/org.kde.pager/contents/ui/main.qml

Is there a way to make patch use the absolute path with any working directory?

Best Answer

Looking at the source code of GNU patch, this behavior is built in since version 2.7. As of GNU patch 2.7.1, only relative paths not containing .. are accepted, unless the current directory is the root directory.

To apply a patch containing absolute paths, you can use

(cd / && sudo patch -p0) <foo.patch

In recent versions of GNU patch, you can simply

sudo patch -d/ -p0 <foo.patch
Related Question