git diff

Estimated reading: 2 minutes 14 views

The git diff command is used to show differences between various states in a Git repository. It compares changes between the working directory, the staging area, and committed snapshots, helping developers track modifications in files.

Optional Commands with git diff

You can enhance the functionality of git diff by using the following options:

OptionDescriptionExample
git diffCompares changes in the working directory with the staging area.git diff shows unstaged changes.
git diff --stagedCompares changes in the staging area with the last commit.git diff --staged shows staged changes.
git diff <branch>Compares changes between the current branch and the specified branch.git diff main shows differences from main.
git diff <commit>Compares the working directory with the specified commit.git diff abc1234 compares with abc1234.
git diff <commit1> <commit2>Compares changes between two specified commits.git diff abc1234 def5678 compares two commits.
git diff -- <file>Displays differences for a specific file.git diff -- example.txt shows changes in example.txt.
git diff --name-onlyLists only the names of changed files.git diff --name-only lists filenames.

Syntax and Example

				
					# Compare working directory changes with the staging area
git diff
# Example output:
# diff --git a/example.txt b/example.txt
# index abc1234..def5678 100644
# --- a/example.txt
# +++ b/example.txt
# @@ -1,3 +1,3 @@
# -Old content
# +New content

# Show staged changes ready to be committed
git diff --staged
# Example output:
# diff --git a/example.txt b/example.txt
# index def5678..ghi7890 100644
# --- a/example.txt
# +++ b/example.txt
# @@ -1,3 +1,3 @@
# -New content
# +Final content

# Compare the current branch with the `main` branch
git diff main
# Example output:
# diff --git a/example.txt b/example.txt
# index ghi7890..jkl0123 100644
# --- a/example.txt
# +++ b/example.txt
# @@ -1,3 +1,3 @@
# -Final content
# +Content from main branch

				
			

Why Use git diff?

  • Track Modifications: See what has changed before committing or staging.
  • Compare Branches: Analyze differences between branches for better merging decisions.
  • Detailed Analysis: Provides line-by-line insights into file changes.

Conclusion

The git diff command is a crucial tool for understanding changes in a Git repository. By providing detailed comparisons, it ensures developers are fully aware of modifications before moving forward in the workflow.

Leave a Comment

Share this Doc

git diff

Or copy link

CONTENTS