tech

Git Stash: Save Your Work Without Committing

While working on a project, sometimes you need to switch branches or pull new changes, but your work is not ready to commit yet. This is where Git Stash becomes very useful.

Git stash lets you temporarily save your uncommitted changes, clean your working directory, and then bring those changes back later.

What is Git Stash?

'git stash' takes your modified files (staged and unstaged) and stores them in a safe place. Your working directory becomes clean, just like the last commit.

You can think of stash as a clipboard for your code.

Basic Git Stash Commands:

1. Stash your changes

This saves all your uncommitted changes and resets your working directory.

git stash

2. Stash with a message

Adding a message helps you remember why you stashed the changes.

git stash push -m "work in progress on login page"

3. View all stashes

git stash list

example output

stash@{0}: On main: work in progress on login page
stash@{1}: On feature: navbar UI update

4. Apply the latest stash

This restores the changes but keeps the stash in the list.

git stash apply

5. Apply and remove the stash

This restores the changes and deletes the stash after applying.

git stash pop

6. Apply a specific stash

git stash apply stash@{1}

7. Drop a stash

This deletes a specific stash.

git stash drop stash@{0}

8. Clear all stashes

This removes all stashed changes permanently.

git stash clear

Example Usage Scenario

Imagine you are working on a feature and suddenly your manager asks you to fix a production bug.

Step 1: Save your current work

git stash push -m "halfway login form"

Step 2: Switch branch and fix the bug

git checkout main

Step 3: Come back and restore your work

git checkout feature/login
git stash pop

Your unfinished work is back exactly as it was.

When Should You Use Git Stash?

  • When you need to quickly switch branches

  • When your work is not ready to commit

  • When pulling new changes causes conflicts

  • When you want to keep your commit history clean

Conclusion

Git stash is a powerful feature that helps you manage unfinished work without committing it. By using stash correctly, you can work faster, switch contexts easily, and keep your repository clean.

Related Articles