Linux 中的 patch 和 diff 命令完全指南
什么是 diff 和 patch?
diff 和 patch 是一对相辅相成的工具,用于比较文件差异和应用补丁。简单来说:
- diff:比较两个文件/目录的差异,生成补丁文件
- patch:将 diff 生成的补丁应用到原文件上
流程示意:
原文件 (old.txt) --[diff]--> 新文件 (new.txt) --[生成]--> 补丁文件 (patch.diff)
补丁文件 (patch.diff) + 原文件 --[patch]--> 更新后的文件
diff 命令详解
基本语法
diff [选项] 原文件 新文件
输出格式对比
| 格式类型 | 命令选项 | 特点 | 适用场景 |
|---|---|---|---|
| 正常格式 | diff (默认) | 最基础的格式,显示需要修改的行 | 简单文件比较 |
| 上下文格式 | diff -c | 显示修改前后的上下文内容 | 代码审查,需要了解上下文 |
| 统一格式 | diff -u | 紧凑显示,包含上下文,最常用 | 生成补丁文件,版本控制 |
实战示例
假设我们有两个版本的配置文件:
config-v1.txt
# 服务器配置 port=8080 host=localhost debug=false max_connections=100
config-v2.txt
# 服务器配置 port=9090 host=0.0.0.0 debug=true max_connections=200 timeout=30
1. 正常格式输出
$ diff config-v1.txt config-v2.txt
2,4c2,5
<port=8080
<host=localhost
<debug=false
<max_connections=100
---
>port=9090
>host=0.0.0.0
>debug=true
>max_connections=200
>timeout=30
输出格式说明:
2,4c2,5:表示原文件第 2-4 行被修改为第 2-5 行。
2. 上下文格式输出
$ diff -c config-v1.txt config-v2.txt
*** config-v1.txt
--- config-v2.txt
***************
*** 1,6 ****
# 服务器配置
!port=8080
!host=localhost
!debug=
!max_connections=100
--- 1,7 ----
!port=9090
!host=0.0.0.0
!debug=
!max_connections=200
+ =30


