Git·19 questions

What is git stash and how to use it?

Answer

git stash saves uncommitted changes to a temporary storage, returning the working directory to the state of the last commit. This is useful when you need to switch to another branch but current changes aren't ready for a commit.

Saving: git stash saves changes in the index and working directory. By default, stash doesn't include untracked files — use git stash -u to include them. You can add a description: git stash push -m "work on auth".

Viewing: git stash list shows all saved stash entries. Each entry looks like stash@{0}, stash@{1}, etc. The command git stash show stash@{0} shows files in a specific entry, and git stash show -p stash@{0} shows the diff.

Restoring: git stash pop applies the latest entry and removes it from the list. The command git stash apply stash@{1} applies an entry but doesn't remove it — useful if you want to apply changes in multiple branches. If pop causes conflicts, the entry is not removed, and you can resolve conflicts manually.

Deleting: git stash drop stash@{0} removes a specific entry. The command git stash clear removes all entries — use with caution.

Practical scenario: you're working on a feature branch, an urgent bug appears in main. You run git stash, switch to main, fix the bug, commit, return to the feature branch and run git stash pop — changes are restored.

Limitation: stash is stored locally and doesn't sync with remote. If you need to transfer changes between machines, better create a temporary branch and commit there.

Was this answer helpful?

More questions in this topic

Related questions from other topics