shell中的diff与patch命令详解

1.diff命令

diff通常比较文件的内容

命令形式为:

diff  file1 file2
diff -r dir1 dir2

其中:

比较文件比较是以第二个文件(file2)为基准的,即file1怎样改变可以成为file2
比较目录时,比较的是目录中文件的不同,而不是文件内容的不同
diff命令比较结果中:

a 表示添加 ----add
c 表示更改 ----change
d 表示删除 ----delete
< 表示第一个文件中的内容, 
> 表示第二个文件中的内容,
 ---   表示分割线

实例1.比较文件内容:

[root@desktop mnt]# cat file1
123
haha
[root@desktop mnt]# cat file2
123
nihao
[root@desktop mnt]# diff file1 file2        #注意是以第二个文件为基准的
2c2                     #第一个文件的第2行 修改变成 第二个文件的第2行
< haha         #< 表示第一个文件中的内容 
---
> nihao        #> 表示第二个文件中的内容

上述比较结果表示file1的第二行和file2第二行的内容不同,改变file1的第二行就可以变成file2

实例2.比较目录

[root@100 mnt]# diff -r /etc/ /mnt/                     >>>>>比较目录需要加上-r,比较的结果是目录中文件的不同,而不是文件内容的不同
 
Only in /etc/: abrt
Only in /etc/: adjtime

patch命令

patch常用来打补丁,使第一个文件打上补丁后与第二个文件相同,补丁可以通过diff -u 命令产生,产生补丁后可以输出到文件中,之后通过patch命令打补丁

以下是一个patch命令使用的实例:

1.生成补丁

.
[root@100 mnt]# diff -u file2 file1      #-u 产生补丁  注意:这里一定是和后者做比较
--- file2	2018-06-10 10:38:12.882174676 -0400
+++ file1	2018-06-10 10:43:30.352174676 -0400
@@ -1,2 +1 @@
 123
-nihao
[root@100 mnt]# diff -u file2 file1 > file2.path     #把补丁导入.path文件,注意后缀,注意是以后一个文件为基准,补丁是对前一个打补丁
[root@100 mnt]# ls
file1  file2  file2.path

2.打补丁

注意: 若没有patch打补丁软件需要先安装软件

[root@100 mnt]# ls
file1  file2  file2.path
[root@100 mnt]# yum install patch -y         #安装patch打补丁软件
[root@100 mnt]# cat file1
123
[root@100 mnt]# cat file2
123
nihao
[root@100 mnt]# cat file2.path                    #查看补丁
--- file2	2018-06-10 10:38:12.882174676 -0400
+++ file1	2018-06-10 10:43:30.352174676 -0400
@@ -1,2 +1 @@
 123
-nihao
[root@100 mnt]# patch file2 file2.path     #给file2打补丁,此时file2和file1就一样了
patching file file2
[root@100 mnt]# cat file2
123

#这样打补丁后原文件就没有了

[root@100 mnt]# ls
file1  file2  file2.path        

3.保留原文件并打补丁

patch命令加-b参数可以保留原文件打补丁,原文件被保存为原文件名.orig文件

[root@100 mnt]# cat file3
123
haha
[root@100 mnt]# cat file1
123
[root@100 mnt]# diff -u file1 file3 > file1.path        #生成file1的补丁
[root@100 mnt]# patch -b file1 file1.path               #-b,打补丁的同时,备份原文件
patching file file1
[root@100 mnt]# cat file1                 #此时file1和file3的内容一样了
123
haha
[root@100 mnt]# ls                #保留了原文件,file1.orig就是原文件
file1  file1.orig  file1.path  file2  file2.path  file3
发布了94 篇原创文章 · 获赞 1 · 访问量 1777

猜你喜欢

转载自blog.csdn.net/qq_36417677/article/details/104398385