Git & GitHub Course
Git & GitHub
/
Intermediate

git stash

Definition

Temporarily shelves (or stashes) changes you've made to your working copy so you can work on something else, and then come back and re-apply them later.

Explain Like I'm New

The panic button. You are halfway through coding a feature when your boss yells 'EMERGENCY BUG ON MAIN BRANCH!'. You can't commit your feature because it's half-broken. You run `git stash`. Git scoops up all your messy desk papers and shoves them in a drawer, leaving you with a perfectly clean desk to fix the bug. Later, you run `git stash pop` to pull the papers back out of the drawer.

Real World Example

Switching branches when you have dirty, uncommitted files in your Working Directory.

Common Use Cases

  • •Context switching safely
  • •Cleaning the working directory without losing work

Terminal Output

bash / terminal
# 1. You are coding, but need to switch branches urgently. $ git stash # Output: Saved working directory and index state WIP on main # 2. Your working directory is now clean! Switch branches safely. $ git checkout hotfix-branch # ... fix the bug, commit it ... # 3. Switch back to your feature branch. $ git checkout main # 4. Pull your messy code back out of the drawer! $ git stash pop

Interview Questions

basic

  • What command puts your stashed files back into your Working Directory?

intermediate

  • Does `git stash` save brand new, untracked files?

Flash Cards

Question

Command to restore?

Click to reveal answer
Answer

`git stash pop`

Question

Untracked files?

Click to reveal answer
Answer

By default, NO. If you created a brand new file, `git stash` will leave it sitting there. You must use `git stash -u` (include untracked) to stash everything.