Git stash
The `git stash` command sets aside uncommitted edits in your local repository so you can work on something else and restore them later without adding a commit to your branch.
Also known as: стэш, git stash
When to use a stash
You're halfway through a change when a teammate asks you to review a fix on another branch. Git doesn't always require a clean working tree to switch branches: it may carry your edits along, or it may refuse the switch if those edits would be overwritten. A stash lets you set your work aside so the review starts without your unrelated edits.
What Git saves
By default, git stash push records changes to tracked files from both the working tree and the index. The index is the staging area: it holds the changes you've selected with git add for the next commit. Git removes the saved changes from both places without moving the tip of your branch.
A file you've just created and never added to Git is untracked, so a plain stash leaves it in place. Use -u (--include-untracked) to save and remove untracked files too. Use -a (--all) only if you also mean to include ignored files, such as generated build output. Stash entries are local to the repository, not owned by a branch, and aren't sent by an ordinary git push.
Example: put a feature on hold
Suppose you're on feature/search and need to switch to an existing branch named review/fix. Check what you've changed, then give the stash a message so you can identify it later:
git status --short
git stash push -u -m 'Search filter in progress'
git switch review/fix
When you're done reviewing, return to the feature. List the stashes, inspect the patch, and apply the entry you want:
git switch feature/search
git stash list
git stash show -p 'stash@{0}'
git stash apply 'stash@{0}'
stash@{0} means “newest entry,” so check the message in the list rather than assuming it still points to your search work. Once you've verified that the changes are back, git stash drop 'stash@{0}' removes the saved copy if it's still the newest entry.
Common mistakes and interview questions
- Why use
applyinstead ofpop?applykeeps the entry, so you can check the result before deleting it.popapplies the changes and drops the entry on success. If there are conflicts, the entry stays in the stash list and you resolve the conflicts in the working tree. - Does applying a stash stage the same edits again? Not by default. If you need the original split between staged and unstaged changes, use
git stash apply --indexto ask Git to restore the index too. - Can you restore a stash onto a different branch? Yes, but restoring isn't an overwrite. Git applies the saved changes against the current state, and overlapping edits can cause conflicts.
Use a stash for a short interruption. If you need a durable checkpoint, a remote copy, or a handoff to a teammate, commit the work on a separate branch and push it when appropriate.