git stash lets you temporarily set aside uncommitted changes so you can switch to a different, more urgent branch and come back to your original work later without committing half-finished code.
Key Points: • git stash saves both staged and unstaged changes and restores the working directory to match HEAD. • git checkout -b new-branch-name creates a fresh branch for the urgent task from the correct base branch. • Once the urgent work is done and committed, you switch back to the original branch (feature-x) with git checkout. • git stash pop reapplies the stashed changes and removes them from the stash list; git stash apply does the same but keeps the entry. • Multiple stashes can coexist and be listed with git stash list if you need to pause more than one piece of work.
Example: While mid-way through feature-x, an urgent bug comes in; you run git stash, then git checkout -b hotfix/urgent-bug main, fix and push the bug, then git checkout feature-x and git stash pop to resume exactly where you left off.
Code Example:
git stash
git checkout -b hotfix/urgent-bug main
# fix and commit the bug
git checkout feature-x
git stash popInterview Tip: A concise interview answer is:
"I'd stash my uncommitted changes with git stash, then branch off for the urgent task from the correct base. Once that's handled, I switch back to feature-x and run git stash pop to restore exactly where I left off."