What is the difference between git diff and git diff –staged?

git diff and git diff --staged are two commands in Git, a distributed version control system, that are primarily used to examine changes made in your codebase. While they may appear similar, they are actually used for different purposes.

1. git diff:

git diff is a command that shows differences between your working directory and the index (also known as the staging area). It’s helpful to identify changes that have been made but not yet staged for commit. In other words, it shows what you’ve modified but haven’t added to the queue to be committed to the repository yet.

If you modify a file and want to see what lines you’ve changed before you stage the changes, you can use git diff. It’ll provide a line-by-line breakdown of what has been added (marked with a ‘+’) and what has been removed (marked with a ‘-‘).

2. git diff –staged:

On the other hand, git diff --staged (in Git versions 1.6.1 and later, you can also use git diff --cached) shows you the difference between the index and the most recent commit. It’s used to view what you’ve staged that will go into your next commit. Essentially, it allows you to review what you’re about to commit, giving you one last chance to ensure that your next commit contains exactly what you want.

To summarise, while git diff shows unstaged changes, git diff --staged shows staged changes. If you don’t see any output from running git diff --staged, it means nothing new has been added to the staging area, so there will be nothing new in the next commit.

Here is a quick visualization of where these commands operate:

| Your repository | Index (Stage) | Working Directory |
|-----------------|---------------|-------------------|
|    git diff --staged    |       git diff      |

A common workflow with Git is to edit files, stage those changes, review the changes, then commit. These two commands come into play in the reviewing stage so that you can carefully curate your commits to have meaningful changesets.