๐Ÿ“ฆ

Using git stash Properly

When You Need to Switch Branches Mid-Work

Sometimes you're mid-change and suddenly need to jump to another branch. The changes are too rough to commit but too valuable to throw away.

That's what git stash is for.

How it works

git stash push saves tracked-file changes to a stack and resets the working tree to HEAD. Later, git stash pop brings them back.

Use -u to include untracked files, -a to include ignored ones too.

stash is a stack

You can pile up multiple entries. git stash list shows them; git stash apply stash@{2} grabs a specific one. pop restores and removes; apply only restores.

Name your stashes

Use git stash push -m 'pausing refactor'. Without a message, three days later you'll have three 'WIP on main' entries and no idea which is which.

Stash instead of destructive commands

git checkout -- ., git reset --hard, git clean -fd permanently wipe changes. If you need to switch branches, always start with stash. Restore with stash pop when you come back.

How It Works

1

`git stash push -m "msg"` -> save changes, clean working tree

2

`git stash list` -> list stacked stashes

3

`git stash pop` -> restore and drop the top stash

4

`git stash apply stash@{N}` -> restore specific entry without dropping

5

`git stash drop stash@{N}` / `git stash clear` -> delete

Pros

  • Safely empties the working tree
  • Stash history separate from reflog

Cons

  • Easy to forget once buried
  • Can hit merge conflicts on pop

Use Cases

Switching branches for an urgent bugfix Holding local changes before pull --rebase Clearing the tree before cherry-pick or merge