Stashing in Git temporarily saves your uncommitted changes so you can switch branches or work on something else without losing your progress. This page explains how to use Git stash effectively.
Stashing allows you to:
- Save your working directory’s changes (tracked and untracked files) without committing them.
- Return to a clean state while preserving your progress for later.
- Stashed changes are stored in a stack-like structure.
- You can apply or discard stashed changes at any time.
- Context Switching: Quickly switch branches to address an urgent issue.
- Clean Environment: Test or experiment in a clean working directory without committing temporary changes.
- Organized Workflow: Avoid unnecessary or incomplete commits.
To stash your changes:
git stash
This stashes:
- Modified tracked files.
- Staged changes.
To add a description for your stash:
git stash push -m "Work in progress for feature X"
To see all stashed changes:
git stash list
Example output:
stash@{0}: On feature: Work in progress for feature X
stash@{1}: On main: Temporary fix
To apply changes from the latest stash:
git stash apply
To apply a specific stash by its identifier:
git stash apply stash@{1}
To apply the changes and remove the stash from the list:
git stash pop
To delete a specific stash:
git stash drop stash@{0}
To remove all stashed changes:
git stash clear
By default, git stash
does not include untracked files. To stash untracked files:
git stash push -u
This includes untracked files in the stash.
To include both untracked and ignored files:
git stash push -a
Modify a file in your working directory:
echo "Work in progress" >> file.txt
Save your changes:
git stash push -m "Work on feature X"
Switch to another branch to work on something else:
git checkout main
Switch back to your branch and apply the stash:
git checkout feature
git stash apply
- Add Messages: Use descriptive messages to identify stashes easily.
- Keep Stash Clean: Regularly review and clear unnecessary stashes.
- Minimize Dependencies: Avoid stashing for long periods as the base branch may change significantly.
Command | Description |
---|---|
git stash |
Stash tracked changes. |
git stash push -m "message" |
Stash with a message. |
git stash push -u |
Stash including untracked files. |
git stash apply |
Apply the latest stash without removing it. |
git stash pop |
Apply and remove the latest stash. |
git stash list |
View all stashes. |
git stash drop stash@{n} |
Remove a specific stash. |
git stash clear |
Remove all stashes. |
Each stash is stored in a stack. You can access specific stashes using their identifiers, such as stash@{0}
.
Yes, use the --keep-index
option to stash only unstaged changes:
git stash push --keep-index
Stashing is a powerful tool for managing temporary changes, allowing you to switch contexts or clean up your working directory without committing incomplete work. By mastering stashing, you can maintain an efficient and organized workflow.
Next Steps: Git Hooks