32-git-27-diff

概述

git diff命令用于查看文件之间的差异。

命令

工作区与暂存区

查看工作区与暂存区的差异

git diff

查看工作区与暂存区某个文件的差异

git diff [file]
git diff file.txt
// 或
git diff -- [file]
git diff -- ./[file]

查看工作区与暂存区多个文件的差异,以空格分隔

git diff -- [file1] [file2]

查看工作区与暂存区目录下所有文件的差异

git diff -- [dir]/

工作区与commit快照

查看工作区与上一次commit之间的差异

git diff HEAD

查看工作区与某个 commit 的差异

git diff [commit]

当我们修改工作区的内容后,我们没有暂存,也没有提交,所以此时暂存区和仓库的状态是相同的。

即此时git diffgit diff HEAD返回的结果是完全相同的


当我们执行git add命令后,此时git diff不会显示任何内容,因为此时工作区与暂存区没有差异。

但是如果执行git diff HEAD命令,仍然可以查看到工作区和提交之间的差异。


假如此时再次修改工作区的内容,我们就能同时对比工作区和(暂存区/仓库)的差异

并且此时暂存区和仓库也是有差异的

暂存区与仓库区

查看暂存区与当前 commit 的差异

git diff --cached

对比两次提交

显示两次提交之间的差异

git diff [first-commit] [second-commit]

我们也可以使用引用,更加方便的对比,比如:最新提交和上一次提交

git diff HEAD HEAD~

对比两个分支

即对比两个分支上最新提交之间的差异

git diff [first-branch] [second-branch]
git diff master dev
// 等效于
git diff [first-branch]..[second-branch]
git diff maste..dev

查看自从topic分支建立以后,master分支发生的变化

git diff topic...master

总结

查看工作区与暂存区的差异

git diff

查看工作区与上一次commit之间的差异

git diff HEAD

查看暂存区与当前 commit 的差异

git diff --cached