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 indev
since diverging frommain
. - 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
- Compare a file:
git diff staging production -- config.yml
- See all differences:
git diff staging..production
- Check commit history:
git log --oneline staging..production -- config.yml
Summary Table
Task | Command |
---|---|
Compare a file | git diff branch1 branch2 -- path/to/file |
Compare all files | git diff branch1..branch2 |
Compare current vs. another | git diff other-branch -- file |
View commit differences | git log --oneline branch1..branch2 -- file |
Use these commands to analyze changes between branches efficiently!