What is Git Stash: Save and Restore Changes Easily
git, stash is a command that temporarily saves your uncommitted changes so you can work on something else without losing your progress. It acts like a clipboard for your code changes, letting you switch branches or tasks and then restore those changes later.How It Works
Imagine you are writing a letter but suddenly need to answer a phone call. You don’t want to lose your place, so you quickly fold the letter and put it aside. git stash works similarly by "folding" your current changes and putting them away safely.
When you run git stash, Git takes all your uncommitted changes—both staged and unstaged—and saves them in a special place called the stash stack. Your working directory then returns to the last committed state, letting you switch branches or work on something else without interference.
Later, you can "unfold" your saved changes with git stash apply or git stash pop, which restores your work exactly as it was before stashing.
Example
This example shows how to stash changes, switch branches, and then restore the changes.
git status # Shows modified files git stash # Saves changes and cleans working directory git checkout main # Switch to main branch git stash apply # Restores stashed changes without removing them from stash git stash pop # Restores and removes the latest stash
When to Use
Use git stash when you need to quickly save your work without committing it. For example:
- You are halfway through a feature but need to fix a bug on another branch.
- You want to pull updates from a remote branch but have uncommitted changes.
- You want to experiment with code but keep your current work safe.
Stashing helps keep your work organized and prevents accidental commits of unfinished code.
Key Points
- Temporary save: Stash saves uncommitted changes without committing.
- Multiple stashes: You can save multiple stashes and apply them later.
- Safe switching: Allows switching branches without losing work.
- Restore easily: Use
git stash applyorgit stash popto get changes back.