11. Git Stashing

Imagine you are working in the middle of a complex, experimental feature on a branch, and suddenly an urgent bug report comes in for production. You need to switch back to the stable branch and fix the bug immediately. However, Git will not let you switch branches if you have uncommitted, conflicting changes in your working directory!

You don't want to make a messy "WIP" commit just to switch branches. This is exactly where Git Stashing comes in.

What is a Stash?

Stashing takes your modified, tracked working directory and staging area, **shelves it temporarily**, and returns your files to a clean state. It stores your changes on an internal stack, allowing you to switch branches, do other work, and then retrieve your changes exactly where you left off later!

The Stashing Commands

1. Shelving Work: git stash

To save all your modified tracked files and clean your working directory, run:

git stash

If you want to add a custom descriptive message to help you identify your stash later:

git stash save "Working on complex dashboard UI layouts"
Note: By default, git stash only saves **tracked** files. If you want to stash untracked files as well, add the -u (or --include-untracked) flag:
git stash -u

2. Listing Your Stashes: git stash list

You can stash multiple times on different branches. Git stores them in a stack sequence. To see all your stashed work:

git stash list

This prints a list of stashes with their indices:

stash@{0}: On feature/dashboard: Working on complex dashboard UI layouts
stash@{1}: On main: WIP on landing page logo change

3. Restoring Your Stash

When you return to your feature branch and want to restore your stashed work, you have two options:

Option A: Apply and Remove: git stash pop (Most Common)

Restores the latest stash (stash@{0}) onto your active working directory and **removes it** from the stash stack:

git stash pop

Option B: Apply and Keep: git stash apply

Restores the stashed changes but **leaves the stash intact** on the stack. This is useful if you want to apply the same stashed changes to multiple branches:

git stash apply

To apply a specific stash from your list instead of the latest one, specify its index reference:

git stash apply stash@{1}

4. Cleaning Up Stashes

To manually delete a specific stash from your list:

git stash drop stash@{0}

To wipe out all stashes on your stack completely:

git stash clear