How to Stash Changes in Git
Set aside uncommitted work with git stash, switch branches on a clean tree, then bring the changes back later with pop or apply.
You have half-finished changes in your working tree and need to switch branches or pull without committing them. Stash the changes, do the other work, then bring them back.
Stash your changes
git stash
Git saves your modified tracked files and staged changes, then resets the working tree to match the last commit. Untracked files (new files you have not added) are left alone by default. To include them:
git stash -u
To label the stash so you can recognize it later:
git stash push -m "wip: login form validation"
List what you have stashed
git stash list
stash@{0}: On main: wip: login form validation
stash@{1}: WIP on feature/search: 3f2a1c9 Add search endpoint
The newest stash is always stash@{0}.
Do the other work
Switch branches, pull, or make an unrelated fix. Your working tree is clean, so nothing blocks you.
git switch main
git pull
git switch -
Bring the changes back
git stash pop
This reapplies the newest stash and deletes it from the list. To reapply a specific one, name it:
git stash pop stash@{1}
If you want the stash to stay in the list after applying (for example, to apply the same changes on two branches), use apply instead:
git stash apply
Inspect a stash before applying it
git stash show -p stash@{0}
This prints the full diff so you can confirm it is the one you want.
If you no longer need a stash. git stash drop stash@{0} removes one entry, and git stash clear removes all of them. Both are permanent, so check git stash list first.
If pop reports a conflict. A stash reapplies like a merge, so if the branch changed the same lines, Git marks the conflicts in the files and leaves the stash in the list. Fix the markers, git add the files, then run git stash drop to remove the stash by hand.
More Coding how-tos
- How to Add a .gitignore File
- How to Check Which Node.js Version Is Installed
- How to Check Which Python Version Is Installed
- How to Clone a Git Repository
- How to Connect to a Server with SSH
- How to Create a New Git Branch
- How to Create a Python Virtual Environment
- How to Delete a Git Branch
- How to Install Node.js with nvm
- How to Install Python Packages with pip
- How to Make a Script Executable in the Terminal
- How to Print Hello World in JavaScript
- How to Print Hello World in Python
- How to Read a JSON File in Python
- How to Resolve a Merge Conflict in Git
- How to Run a Local Web Server in One Command
- How to Set an Environment Variable
- How to Undo the Last Git Commit
- How to Write Your First Bash Script