Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is it possible to know if a file has been patched already, before apply the patch?

I need to do this in a script, any thoughts?

share|improve this question
What program are you using to patch them? What sort of patches? – Omnifarious Nov 15 '12 at 4:05
The key is "-R" — unix.stackexchange.com/a/86872/6622 – poige Aug 15 '13 at 14:05

Just in case it helps someone, if you are using bash script then the example given by Omnifarious would not work. In bash the exit status of a successful command is 0

So the following would work:

patch -p0 -N --dry-run --silent < patchfile 2>/dev/null
#If the patch has not been applied then the $? which is the exit status 
#for last command would have a success status code = 0
if [ $? -eq 0 ];
    #apply the patch
    patch -p0 -N < patchfile
share|improve this answer
The checking should be against 1 instead of 0: if [ $? -eq 1 ] – Crisson Dec 20 '15 at 5:46

Yep, just run patch with --dry-run option, it either would fail or succeed which can be found out with its exit status.

But in more common (and error prone) way, you probably have to run it with -R option which means "reverse" since only if it was able to revert the whole patch it could be considered as "applied". Otherwise (without '-R') it could fail just due to some parts of the original file was changed. Below is a simple example:

if ! patch -R -p0 --dry-run <patchfile; then
  patch -p0 <patchfile
share|improve this answer

Here is a guess, assuming that you are using the patch utility and each file to be patched has its own patch:

if nohup patch <options> -N --dry-run --silent <patchfile 2>/dev/null; then
    echo The file has not had the patch applied,
    echo and the patch will apply cleanly.
    echo The file may not have had the patch applied.
    echo Or maybe the patch doesn't apply to the file.
share|improve this answer
Or, if you patched the files before and want to know, whether it touched some specific file, you can run the first patch round with the -B option, which would cause backup to be made. Then you check for existence of the backup. – peterph Nov 15 '12 at 10:12
Could you expand a bit on why you chose to use nohup in that if case? – zrajm Apr 17 '13 at 12:48

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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