Linux patch 命令用于为软件打补丁,使用
diff命令获取软件的变更。patch 是 linux 核心升级的方法之一。下面介绍如何制作和应用 patch 补丁。
安装
yum install -y patchhelp
补丁制作命令 diff
diff 可以比较两个文件或文件夹的区别。制作补丁时的一般用法和常见选项为:
diff [选项] 源文件(夹) 目的文件(夹)- -r 递归,设置后 diff 会将源/目的文件夹的全部文件进行比较,包括子目录中文件
- -N 确保补丁文件正确地处理创建或删除文件的情况
- -u
输出每个修改前后行数,-u 3 :输出修改前后 3 行 - -忽略内容
- -i, –ignore-case ignore case differences in file contents
- -E, –ignore-tab-expansion ignore changes due to tab expansion
- -Z, –ignore-trailing-space ignore white space at line end
- -b, –ignore-space-change ignore changes in the amount of white space
- -w, –ignore-all-space ignore all white space
- -B, –ignore-blank-lines ignore changes where lines are all blank
- -I, –ignore-matching-lines=RE ignore changes where all lines match RE
- –strip-trailing-cr strip trailing carriage return on input
补丁制作命令 git diff
$ git diff > mock.patch
$ cat mock.patch
diff --git a/origin.txt b/origin.txt
index bdf5010..fba3718 100644
--- a/origin.txt # --- 表示旧文件
+++ b/origin.txt # +++ 表示新文件
@@ -1,3 +1,3 @@ # 修改的信息
hello line 1 # 原始文件默认做进一个空格
-this is origin file # - 表示删除的行
+this is new file # +表示新增的行
hello line 2补丁制作命令 git format-patch
使用 git format-patch 生成相关 patch,示例如下:
# 最近1次提交
git format-patch HEAD^
# 最近2次提交
git format-patch HEAD^^
# 生成指定(不含)提交之后的所有提交
git format-patch <commit>
# 生成指定(含)提交
git format-patch -1 <commit>
# 生成指定(含)提交之前的n次提交
git format-patch -n <commit>patch 命令
patch 常用参数说明:
patch -pNUM -i <patchfile>-
-p Num 忽略几层文件夹,
0001-abc.patch示例:--- a/xxx/origin.txt +++ b/xxx/origin.txt- -p0 表示在当前目录找
xxx/origin.txt文件 - -p1 表示忽略
xxx目录,在当前目录找origin.txt文件
- -p0 表示在当前目录找
-
-E 如果发现了空文件就删除它
-
-R 回滚打过的补丁
使用示例
# 原始文件 origin.txt,新文件 new.txt
$ cat origin.txt
hello line 1
this is origin file
hello line 2
$ cat new.txt
hello line 1
this is new file
hello line 2
# 制作patch文件
$ diff origin.txt new.txt >> mock.patch
$ cat mock.patch
2c2
< this is origin file
---
> this is new file
# 在 origin.txt 中应用 mock.patch,等同于 patch -p0 origin.txt -i mock.patch
$ patch -p0 origin.txt < mock.patch
patching file origin.txt
# 打 patch 后 origin.txt 内容
$ cat origin.txt
hello line 1
this is new file
hello line 2
# 回滚 mock.patch
$ patch -p0 -R origin.txt < mock.patch
patching file origin.txt
# 回滚后 origin.txt 内容
$ cat origin.txt
hello line 1
this is origin file
hello line 2注意:若生成 *.rej 文件,表示 patch 应用失败。
扩展
制作布丁的命令:
- quilt
- diff
- git diff
F&Q
Hunk #2 FAILED at 345. 1 out of 2 hunks FAILED – saving rejects to file
patch --ignore-whitespace 的作用是在应用补丁时忽略空白字符(空格、制表符、换行等)的差异,从而减少因代码格式调整(如缩进、行尾空格等)导致的补丁冲突
如果你在使用 Git,可以尝试:
git apply --reject your.patchGit 会尝试自动应用能匹配的 hunk,并将冲突的 hunk 保存到 .rej 文件中,方便手动处理。