Make `patch` return 0 when skipping an already applied patch

Accepted answer did not work for me because patch was returning 1 also on other types of errors (maybe different version or sth). So instead, in case of error I am checking output for "Skipping patch" message to ignore such but return error on other issues.

OUT="$(patch -p0 --forward < FILENAME)" || echo "${OUT}" | grep "Skipping patch" -q || (echo "$OUT" && false);

I believe that the following recipe should do the trick, it is what I am using in the same situation;

patches: $(wildcard $(SOMEWHERE)/patches/*.patch)
    for patch_file in $^; do \
        patch --strip=2 --unified --backup --forward --directory=<somewhere> --input=$$patch_file; \
        retCode=$$?; \
        [[ $$retCode -gt 1 ]] && exit $$retCode; \
    done; \
    exit 0

This recipe loops over the dependencies (in my case the patch files) and calls patch for each one. The "trick" on which I am relying is that patch returns 1 if the patch has already been applied and other higher numbers for other errors (such as a non existent patch file). The DIAGNOSTICS section of the patch manual entry describes the return code situation. YMMV


You can also do that as a one line only

patch -p0 --forward < patches/patch-babylonjs.diff || true

So if you want to apply the patch and make sure that's it's working:

(patch -p0 --forward < patches/patch-babylonjs.diff || true) && echo OK

No matter whether the patch has already been applied or not, you'll always get "OK" displayed here.

Tags:

Patch