patch

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


I have a build tool that runs a patch command and if the patch command returns non-zero, it will cause the build to fail. I am applying a patch that may or may not already be applied, so I use the -N option to patch, which skips as it should. However, when it does skip, patch is returning non-zero. Is there a way to force it to return 0 even if it skips applying patches? I couldn't find any such capability from the man page.


Solution

  • 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