Stashing Changes
In Git, stashing changes allows you to temporarily save your uncommitted work so you can switch branches or work on another task without creating a commit. It provides a clean working directory while preserving your unfinished changes.
git stash -u to include untracked files.
1. Common Stash Commands
Save Your Changes
git stash
Saves changes to tracked files and restores your working directory to a clean state.
Save Changes with a Message
git stash push -m "Working on login layout"
Adds a descriptive message to help identify the stash.
List Saved Stashes
git stash list
Displays your saved stashes, such as
stash@{0} and stash@{1}.
Restore and Remove the Latest Stash
git stash pop
Applies the latest stash and removes it from the stash list when the operation succeeds.
Restore Without Removing
git stash apply
Applies the latest stash but keeps it in the stash list so it can be used again.
Include Untracked Files
git stash -u
Includes newly created, untracked files in the stash.
2. Example: Switching Branches Safely
Suppose you are working on a login feature, but you need to switch to another branch to fix an urgent bug.
Step 1: Save Your Work
git stash push -m "Login feature in progress"
Step 2: Switch to the Bug-Fix Branch
git switch bugfix/login-error
Step 3: Complete the Bug Fix
git add .
git commit -m "Fix login error"
Step 4: Return to Your Feature Branch
git switch feature/login
Step 5: Restore Your Changes
git stash pop
Your saved changes are restored so you can continue working on the login feature.
3. When Should You Use Git Stash?
Interrupted Work
Save unfinished changes when an urgent task requires you to work on a different branch.
Before Updating Your Branch
If local changes interfere with an update, stash them temporarily, pull the remote changes, and restore your work.
git stash
git pull origin main
git stash pop
Testing Another Approach
Temporarily save your current work while experimenting with a different implementation.
4. Quick Reference
| Command | Purpose |
|---|---|
git stash |
Temporarily save tracked-file changes. |
git stash push -m "message" |
Save changes with a descriptive message. |
git stash list |
View saved stashes. |
git stash pop |
Apply the latest stash and remove it when successful. |
git stash apply |
Apply the latest stash and keep it saved. |
git stash -u |
Include untracked files. |
git stash drop |
Remove the latest stash without applying it. |
git stash to save unfinished changes,
git stash list to find saved work, and
git stash pop to restore it.