Advanced Git Tools: Stash, Bisect, and Blame
Beyond the day-to-day commands like commit and merge, Git provides a suite of powerful tools designed to help you debug issues, manage interrupted workflows, and understand code history.
1. Git Stash: Saving Interrupted Work
Imagine you are halfway through implementing a feature, but your boss asks you to fix a critical bug on main immediately. Your feature isn't ready to commit, but you can't checkout main with dirty, uncommitted changes.
This is exactly what git stash is for. It takes your uncommitted changes (both staged and unstaged) and saves them away on a stack, leaving your working directory clean.
Basic Stash Workflow
- Stash your work:
git stash # Output: Saved working directory and index state WIP on feature-x... - Switch branches and fix the bug:
git checkout main # ... fix bug, commit ... - Return and pop the stash:
git checkout feature-x git stash popgit stash popapplies the stashed changes back to your working directory and removes them from the stash list.
Useful Stash Commands
git stash list: View all stashes.git stash apply: Apply the stash without deleting it from the list.git stash drop: Delete a specific stash.
2. Git Bisect: The Bug Hunter
git bisect is a life-saving tool when you discover a bug but don't know which commit introduced it. It uses a binary search algorithm to quickly find the offending commit among hundreds or thousands of commits.
How to Bisect
- Start the process:
git bisect start - Mark the current (broken) commit as bad:
git bisect bad - Find an older commit where the feature worked, and mark it as good:
git bisect good v1.0.0 - Git will automatically check out a commit exactly in the middle. You test the code and tell Git if it's
goodorbad. - Repeat step 4. Because it's a binary search, finding a bug in 1,000 commits takes roughly 10 steps!
- End the bisect session:
git bisect reset
3. Git Blame: Who Wrote This?
Despite its aggressive name, git blame is simply a tool for auditing file history. It annotates every line in a file, showing the hash of the commit that last modified the line, the author, and the timestamp.
Using Blame
git blame server.js
Output example:
^9fceb02 (Alice Smith 2023-01-10) const express = require('express');
b4a2c10f (Bob Jones 2023-02-15) const app = express();
88d1f2a3 (Alice Smith 2023-03-01) app.use(express.json());
This allows you to ask the right person why a specific line of code was written a certain way.
Combining Tools
Modern IDEs (like VS Code) and platforms (like GitHub) build "Git Lens" or "Annotate" features directly into the editor, which use git blame under the hood to show inline history.