The git diff Command

Learn about git diff and its variations.

Variations of the git diff command

The git diff command is used to see the differences between any two stages. The following is a list of stages that can be compared using git diff:

  • We can see the difference between the working environment and the staging area—that is, the difference between unstaged changes and staged changes.

    $ git diff
    
  • We can see the difference between the staging area and the last commit.

    $ git diff --staged
    
  • We can see the staged changes (added but not committed) with the last commit in the current branch.

    $ git diff --cached
    

    The --cached and --staged options are the same, more or less.

  • TWe can see the difference between the two branches. The two dots between the two branch names show that we want to read the latest commit in each branch and compare them.

    $ git diff <branch1>..<branch2>
    
  • We can see the difference between two commits by comparing files between them. For that purpose, the reference to the commits needs to be specified. A reference may be a commit ID or HEAD, which refers to the current branch.

    $ git diff <commit1> <commit2>
    

Example of git diff

Let’s look at a basic example to make things more clear.

We have a file named file1.txt to which we’ll make changes and observe the working of git diff.

First, we run the following commands in the terminal below:

 $ echo "Hello" >> file1.txt
 $ git add file1.txt
 $ echo "Hello again" >>  file1.txt
 $ git diff

These commands show the difference between unstaged and staged changes.

Now, we run the following commands:

 $ git add .
 $ git commit -m "Second commit"
 $ echo "Some more changes" >> file1.txt
 $ git add .
 $ git diff --staged

These commands show the difference between the staging area and the last commit.

Get hands-on with 1400+ tech skills courses.