主要用到两个命令
diff:
可以比较两个单文件或目录内容,记录下两者不同
diff [] from to
-r 递归,比较所有子目录下文件
-N 确保补丁文件将正确地处理已经创建或删除文件的情况
-u 输出每个修改前后的3行,也可以用-u6等指定输出上下文行数
patch
将diff的结果(补丁)应用到相应文件/目录上
patch -pN dir/file patchfile
-pN 忽略N层目录,比如-p1,patch会忽略掉第一个“/”之前的内容
-R 取消打过的补丁
举例应用:
(1) 处理单个文件
产生补丁
diff -uN hello.c bye.c > file.patch
补丁内容
点击(此处)折叠或打开
- --- hello.c 2013-06-06 11:38:55.972598077 +0800
- +++ bye.c 2013-06-06 11:39:45.256597688 +0800
- @@ -1,6 +1,6 @@
- #include <stdio.h>
- int main(void)
- {
- - printf("hello,world!rn");
- + printf("bye,world!rn");
- return 0;
- }
- 打上补丁
- cp hello.c test.c
- test.c 内容:
- #include <stdio.h>
- int main(void)
- {
- printf("hello,world!rn");
- return 0;
- }
- patch -p0 test.c < file.patch
- #include <stdio.h>
- int main(void)
- {
- printf("bye,world!rn");
- return 0;
- }
取消补丁
patch -RE -p0 test.c < file.patch
test.c文件还原
(2) 处理目录
diff -uNr old/ new/ > dir.patch
cd old
patch -p1 <../dir.patch
取消目录
patch -R -p1 <../dir.patch
patch文件构成
以下是上例目录补丁的内容
点击(此处)折叠或打开
- diff -uNr old/hello.c new/hello.c
- --- old/hello.c 2013-06-06 10:11:32.724674000 +0800
- +++ new/hello.c 2013-06-06 10:39:21.032652591 +0800
- //补丁头,---表示旧文件,+++表示新文件
- @@ -4,10 +4,12 @@
- //old/hello.c 4~10行,new/hello.c 4~12行为改动区间
- int i,j;
- int ret;
-
- - i = 5;
- j = 6;
- + i = 7
- ret = i + j;
- printf("%d + %d =%drn",i,j,ret);
-
- + printf("hello world!rn");
- +
- return 0;
- }
- //补丁块,-表示这一行是要删除的,+表示这一行是增加的,其他表示无修改
- diff -uNr old/test.c new/test.c
- --- old/test.c 2013-06-06 10:29:49.100659025 +0800
- +++ new/test.c 2013-06-06 10:46:04.732643907 +0800
- @@ -1,6 +1,9 @@
- #include <stdio.h>
- int main(void)
- {
- - printf("testn");
- + printf("test0.rn");
- + printf("test.rn");
- + printf("test1.rn");
- + printf("test2.rn");
- return 0;
- }
最后有以下几点注意:
1. 一次打多个patch的话,一般这些patch有先后顺序,得按次序打才行。
2. 在patch之前不要对原文件进行任何修改
3. 如果patch中记录的原始文件和你得到的原始文件版本不匹配(很容易出现),那么你可以尝试使用patch, 如果幸运的话,可以成功。大部分情况下,会有不匹配的情况,此时patch会生成rej文件,记录失败的地方,你可以手工修改。
使用版本控制工具时,可以svn diff或git diff生产补丁