git-stash-guardar-temporalmente

Git Stash Temporary Storage

  • 4 min

The git stash command is a temporary storage area where Git saves the modifications from your working directory that are not yet ready to be integrated into a commit.

Imagine you are in the middle of a complex task on your feature branch. You have half-edited files, the code doesn’t compile, and everything is a mess.

Then, you get an alert: “Critical bug! Need to fix it NOW”. You have a problem:

  1. You can’t commit because your code is broken and messy.
  2. You can’t switch to the hotfix branch because Git won’t let you change branches with modified files that would cause conflicts.

What do you do? Delete your work? Make a garbage commit called “wip”, switch to hotfix, and then come back? (which wouldn’t be the worst option either).

For these circumstances, Git has a secret weapon, Git’s temporary pocket: git stash.

What is the Stash?

The Stash (hideout/reserve) is a temporary storage area where you can “park” your current changes.

Think of it as a giant Clipboard inside Git.

When you run git stash, Git takes all your changes from the Working Directory and the Staging Area, packages them up, and saves them in a separate area.

The result is that your working directory becomes clean (as if you had just made a commit), allowing you to switch branches without problems.

Basic Commands

To save everything you have in progress, simply run:

git stash
Copied!

You’ll see a message like Saved working directory and index state....

If you do a git status now, you’ll see everything is clean. Now you can go to the main branch, fix the bug, and come back.

Once you’ve finished the emergency and are back on your branch, you want to retrieve your stuff. The command is:

git stash pop
Copied!

This does two things:

  1. Applies the saved changes to your working directory.
  2. Removes those changes from the stash stack (empties it).

If you want to apply the changes but keep a copy in the stash (for safety or to apply it on several branches), use git stash apply instead of pop.

The Untracked Files Problem

By default, git stash only saves files that Git already knows (Tracked). It ignores new files (Untracked).

To save absolutely everything, including new files, you must use the -u option (include untracked):

git stash -u
Copied!

Cleaning the Stash

If you abuse stash, you’ll end up with a list full of garbage. You can delete Stashes.

  • Delete the last stash:
git stash drop
Copied!
  • Delete a specific one:
git stash drop stash@{3}
Copied!
  • Delete EVERYTHING
git stash clear
Copied!