Git diff

Diff between un-staged changes and staged / commuted changes:

$ git diff

This compares the current non-added changes with the last commit in the current branch.

$ git diff --cached

--cached compare the staged changes (added but not committed) with the last commit in the current branch.

$ git diff branchA branchB

Why need to diff before committing?We want to check what’s the changes between the latest code and the last committed code.

Assume the following git status result. We see that there are two files changes. One file is last-save.js.jsx and the other one is app.css.scss.

An example of git status with two changes files:

$ git status
  On branch master

  Changes not staged for commit:
    (use "git add <file>..." to update what will be committed)
    (use "git checkout -- <file>..." to discard changes in working directory)

      modified:   app/assets/javascripts/components/last-save.js.jsx
      modified:   app/assets/stylesheets/app.css.scss

  no changes added to commit (use "git add" and/or "git commit -a")

Then, we use the git diff to check the code changes before committing them into the repository.

In the diff, we find that the 2 files are actually 2 different things. One file is a ReactJS view component and the other is a CSS styling improvement. We didn’t commit before making changes to another feature.

We add 1 file and commit it, then we commit another file. This results in two different commits for two different purposes.