How to Use Git Stash: Save and Restore Changes Easily
Use
git stash to save your uncommitted changes temporarily without committing them. Later, use git stash apply to restore those changes or git stash pop to restore and remove them from the stash list.Syntax
The basic commands for git stash are:
git stash: Saves your current changes and cleans your working directory.git stash apply [stash@{n}]: Restores the saved changes from the stash without removing them.git stash pop: Restores the saved changes and removes them from the stash list.git stash list: Shows all saved stashes.git stash drop [stash@{n}]: Deletes a specific stash.
bash
git stash
git stash apply [stash@{n}]
git stash pop
git stash list
git stash drop [stash@{n}]Example
This example shows how to save changes, list stashes, and restore changes using git stash commands.
bash
echo "Initial content" > file.txt # Make changes echo "New line" >> file.txt # Save changes to stash git stash # Check stash list git stash list # Restore changes git stash apply # Check file content cat file.txt
Output
Saved working directory and index state WIP on main: <commit-hash> Initial commit
stash@{0}: WIP on main: <commit-hash> Initial commit
Initial content
New line
Common Pitfalls
Common mistakes when using git stash include:
- Forgetting to apply or pop the stash, leaving changes hidden.
- Using
git stash applywithout specifying the stash when multiple stashes exist, which applies the latest stash by default. - Assuming
git stash popalways succeeds; conflicts can occur and must be resolved manually. - Not committing important changes before stashing, risking loss if the stash is dropped.
bash
git stash apply stash@{1} # Apply specific stash
git stash pop # Applies and removes stash, but may cause conflicts
# Wrong: expecting stash to be removed after apply
# Right: use pop to remove stash after applyingQuick Reference
| Command | Description |
|---|---|
| git stash | Save current changes and clean working directory |
| git stash list | Show all saved stashes |
| git stash apply [stash@{n}] | Restore changes from stash without removing |
| git stash pop | Restore changes and remove stash |
| git stash drop [stash@{n}] | Delete a specific stash |
Key Takeaways
Use git stash to save uncommitted changes temporarily without committing.
Restore changes with git stash apply to keep stash or git stash pop to remove it.
Always check git stash list to see saved stashes before applying or dropping.
Be careful with conflicts when applying or popping stashes; resolve them manually.
Do not rely on stash as a permanent backup; commit important changes regularly.