0
0
GitHow-ToBeginner · 3 min read

How to Stash Changes in Git: Simple Commands and Examples

Use git stash to save your current changes temporarily without committing. Later, apply them back with git stash apply or git stash pop to continue working.
📐

Syntax

The basic command to stash changes is git stash. You can add a message with git stash save "message" (older syntax) or simply git stash push -m "message" (recommended). To see saved stashes, use git stash list. To reapply changes, use git stash apply or git stash pop (which applies and removes the stash).

bash
git stash push -m "work in progress"
git stash list
git stash apply stash@{0}
git stash pop
💻

Example

This example shows how to stash your changes, switch branches, and then reapply the changes.

bash
mkdir repo && cd repo
git init

echo "Initial content" > file.txt

echo "Line 1" > file.txt
git add file.txt
git commit -m "Add file.txt"

echo "Line 2" >> file.txt

# Stash changes
git stash push -m "Added Line 2"

# Switch branch
git checkout -b new-feature

# Reapply stash
git stash pop
Output
Saved working directory and index state WIP on master: Add file.txt Switched to a new branch 'new-feature' On branch new-feature Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git restore <file>..." to discard changes in working directory) modified: file.txt Dropped refs/stash@{0} (e8a1c2d)
⚠️

Common Pitfalls

  • Forgetting to apply or pop the stash after switching branches can cause confusion about missing changes.
  • Using git stash pop removes the stash; if conflicts occur, changes might be lost if not handled carefully.
  • Stashing untracked files requires git stash push -u or git stash --include-untracked.
  • Older syntax git stash save is deprecated; prefer git stash push.
bash
git stash save "old way"  # Deprecated

git stash push -m "new way"  # Recommended

git stash push -u  # Include untracked files
📊

Quick Reference

CommandDescription
git stash push -m "message"Save changes with a message
git stash listShow all stashed changes
git stash apply [stash@{n}]Reapply stash without removing it
git stash popReapply stash and remove it
git stash push -uStash including untracked files
git stash drop stash@{n}Delete a specific stash

Key Takeaways

Use git stash push to save your work temporarily without committing.
Apply stashed changes with git stash apply or git stash pop to continue working.
Include untracked files in stash with git stash push -u.
Avoid using deprecated git stash save; prefer git stash push.
Always check your stash list with git stash list to manage saved changes.