0
0
GitConceptBeginner · 3 min read

What is Git Stash: Save and Restore Changes Easily

In 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.

bash
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
Output
On branch feature Changes not staged for commit: modified: file.txt Saved working directory and index state WIP on feature: abc1234 Commit message Switched to branch 'main' # No changes in working directory # Changes from stash applied # Stash entry dropped after pop
🎯

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 apply or git stash pop to get changes back.

Key Takeaways

Git stash temporarily saves your uncommitted changes to switch tasks safely.
Use git stash to avoid committing incomplete work when switching branches.
You can apply or pop stashed changes to restore your work later.
Multiple stashes can be saved and managed independently.
Stashing helps keep your working directory clean and organized.