Git - Diff Between Working Dir, Staged Area, Last Commit


How to compare branches/files in git

There are 3 major concepts :

  • Working Directory → files in your working directory.
  • Staging Area (aka cacheindex) → a temp area that git add is placed into.
  • HEAD → A reference to a specific commit (think of it as a variable). Normally, it points to the last commit in local repository. (that is, after you did git commit). [see Git: What's HEAD]

One more concept is Commit ID. Every commit has a ID. The commit id is a 40 digits hexadecimal, for example: 3b6ea398cc2d69212b04c29f06b8d15c0af34e34.

How to get commit ID?

# to show the last 3 commit's commit id

git log -3

 

How to diff between working dir, staging area?

# diff working dir, staging area
git diff --color
# diff working dir, staging area, 1 file
git diff --color filename

 

How to diff between staging area, last commit?

# diff staging area, last commit. (--staged is same as --cached)

git diff --color --staged ‹commitID›

 

How to diff between last commit, working dir?

First, use git log to get a commit ID.

# diff last commit, working dir

git diff --color ‹commitID›

 

How to diff between 2 commits in the same branch?

First do

git log file_name

to find the commits IDs. Then, do

git diff commit_ID_1 commit_ID_2 file_name

git diff 3d5cf 5aa95 myfilename

 

we only need to type the first few characters of commit id.

How to find what files are changed?

git status → get summary of {last commit, staging area, working dir}

# show changes between {staging area, last commit} and {staging area, working dir}
git status .