How to Git- Comparing staging area with the Repository

In version control system, differences between two versions are presented by git diff command.
The most common scenario to use git diff is to see what changes you made after your last commit.
It’s recommended to read the previous tutorial How to create a repository. Let’s take a detailed look comparison.

Comparing unstaged area with the repository

The diff command compares two items with each other. In most cases, both will be the same file, but in different versions. For example, create a file named first.txt on our repository and add some text on it.

 

first.txt

Git comparing staging area with the repository

 

Add the file to stage area commit the file to the repository.

Stage and Commit
   $ git add first.txt

   $ git commit -m "File commited"
   [master b3eb63c] File commited
   1 file changed, 1 insertion(+), 1 deletion(-)


 

Let’s change the text in the first.txt file and save it.

 

first.txt

Git comparing staging area with the repository

 

Open up Git bash and run git diff command to see the difference.

 

Git diff command
   $ git diff
   diff --git a/first.txt b/first.txt
   index af92e7f..aae072d 100644
   --- a/first.txt
   +++ b/first.txt
   @@ -1 +1 @@
   -This is my first file
   \No new line at end of file
   +This file is edited.
   \No new line at end of file

 

The diff command compares two items with each other: a/first.txt and b/first.txt which are the different version of the same file. It will show us all current local changes in our working copy that are unstaged.

 

Comparing staging area with the Repository

To compare staging area with the repository, use git diff --staged command. For example, add first.txt to the stage area. then see the difference using git diff --staged command.

 

comparison with stage area
   $ git add first.txt

   $ git diff --staged
   diff --git a/first.txt b/first.txt
   index af92e7f..aae072d 100644
   --- a/first.txt
   +++ b/first.txt
   @@ -1 +1 @@
   -This is my first file
   \No new line at end of file
   +This file is edited.
   \No new line at end of file

 

Other common diff options are follows

 

Other diff commands
   git diff HEAD [filename] //  compare the working directory with local repository.
   git diff --cached [filename] // compare the index with local repository.

 

 

Muhsin Yakkiparamban

Muhsin Yakkiparamban is the co-founder of Lauyou Learning. Muhsin holds Bachelor Degree in Civil Engineering from KMCT Calicut.

You may also like...