How to compare files from two different branches in Git?

To compare files between two branches in Git, use the git diff command. Here are the key methods with examples:

1. Compare a Specific File Across Branches

Syntax:

git diff <branch1> <branch2> -- <file-path>

Example:

# Compare `app.js` between `main` and `feature/login`
git diff main feature/login -- src/app.js

2. Compare All Files Between Branches

Syntax:

git diff <branch1>..<branch2>

Example:

# Show all differences between `main` and `dev`
git diff main..dev

3. Compare Current Branch to Another Branch

Syntax:

git diff <other-branch> -- <file-path>

Example:

# Compare `styles.css` in your current branch to `main`
git diff main -- assets/styles.css

4. Check Differences in Commit History

Syntax:

git log --oneline <branch1>..<branch2> -- <file-path>

Example:

# List commits affecting `README.md` in `dev` but not in `main`
git log --oneline main..dev -- README.md

Key Notes

  • Order Matters: git diff main dev shows changes in dev since diverging from main.
  • View Changes in Tool: Use git difftool <branch1> <branch2> for a GUI comparison (e.g., VS Code, Meld).
  • Compare to Remote Branches:
  git diff origin/main origin/dev -- package.json

Example Workflow

  1. Compare a file:
   git diff staging production -- config.yml
  1. See all differences:
   git diff staging..production
  1. Check commit history:
   git log --oneline staging..production -- config.yml

Summary Table

TaskCommand
Compare a filegit diff branch1 branch2 -- path/to/file
Compare all filesgit diff branch1..branch2
Compare current vs. anothergit diff other-branch -- file
View commit differencesgit log --oneline branch1..branch2 -- file

Use these commands to analyze changes between branches efficiently!

Leave a Reply

Your email address will not be published. Required fields are marked *