How To Use Git Stash To Save And Manage Uncommitted Changes

You Are in the Middle of a Feature and Need to Switch Branches

You have been heads-down for an hour, refactoring a messy function. The code is not ready to commit, but a critical bug just landed in production. Your team lead asks you to switch to the main branch immediately, run the fix, and deploy. Panic sets in. You cannot commit your half-broken work, and you definitely cannot lose it.

This is the exact moment Git stash becomes your best friend. It is the emergency save button for your uncommitted changes. Instead of forcing a messy commit with a meaningless message or, worse, copying and pasting code into a text file, you can temporarily shelve everything. With one command, your working directory becomes clean, allowing you to jump to another branch, address the fire, and then return to pick up right where you left off.

Mastering git stash is a fundamental skill for any developer working in a collaborative, fast-paced environment. It transforms workflow chaos into controlled, context-switching agility. This guide will walk you through not just the basic save and pop, but the entire toolkit: viewing, applying, managing multiple stashes, and cleaning up. You will learn how to use stash git effectively as a professional.

What Git Stash Actually Does

Before diving into commands, it is crucial to understand the mechanics. The git stash command takes your uncommitted changes—both modified tracked files and staged changes—and saves them on a stack of unfinished work. It then reverts your working directory to match the HEAD commit.

Think of it as a separate, hidden commit that is not part of your branch history. This stack is local to your repository; you cannot push or pull stashes from a remote. The changes stashed can include:

– Modifications to tracked files (the result of git add).
– Changes staged for commit (the result of git add).
– New, untracked files (if you use the -u flag).

It is important to note that by default, git stash will ignore brand new, untracked files. You must explicitly include them, which we will cover.

The Core Commands: Save, List, and Restore

The basic workflow involves three key actions: saving your work, viewing what you have saved, and getting it back.

Stashing Your Current Work

The primary command is simple. From your repository directory, run:

git stash

This is shorthand for git stash push. It takes all modified tracked files and staged changes, bundles them into a new stash entry, and clears your working directory. You will see a message like “Saved working directory and index state WIP on your-branch-name: abc1234 Commit message.”

To include untracked files in this stash, use the -u flag (or –include-untracked):

git stash -u

For the rare case where you also want to stash ignored files, you can use -a (–all).

It is good practice to add a descriptive message, especially if you plan to have multiple stashes. Use the -m flag:

git stash push -m “Refactoring user auth middleware – WIP”

Viewing Your Stash Stack

After stashing, you can see what is on your stack with:

git stash list

This will output something like:

stash@{0}: On feature/login: Refactoring user auth middleware – WIP

how to use stash git

stash@{1}: On main: Quick CSS fix before meeting

The most recent stash is always stash@{0}. The older ones have increasing indices.

To see the detailed diff of what a specific stash contains, use:

git stash show stash@{1}

Add the -p flag for a full patch view:

git stash show -p stash@{0}

Restoring Your Stashed Work

There are two main commands to get your changes back: pop and apply. The difference is critical.

git stash pop

This command takes the most recent stash (stash@{0}), applies its changes to your current working directory, and then deletes that stash from the stack. It is a “take it off the shelf and use it” operation. Use this when you are ready to continue working on those changes and no longer need the stash copy.

git stash apply

This command applies the changes from the most recent stash but leaves the stash entry on the stack. This is useful if you want to apply the same stash to multiple branches, or if you are not yet sure you are done with it. To apply a specific, older stash, specify it:

git stash apply stash@{2}

Be aware that applying a stash can lead to merge conflicts if the underlying code on your current branch has diverged from when you created the stash. Git will pause and ask you to resolve these conflicts, just like a standard merge.

Advanced Stash Management for Real Workflows

Basic save and pop will handle 80% of cases. For the other 20%, these advanced techniques are lifesavers.

Creating a Branch from a Stash

Sometimes, you stash work, then realize the context has changed so much that applying it directly would be a mess. The best solution is to create a new branch starting from the exact point where you created the stash.

git stash branch new-branch-name stash@{1}

This powerful command does three things at once: it creates a new branch named `new-branch-name` starting from the commit that was HEAD when you made the stash, applies the specified stash to that branch’s working directory, and then drops the stash if the application is successful. It is the cleanest way to resurrect old, context-dependent work.

Selectively Stashing Changes (Interactive Stash)

You do not always want to stash everything. Imagine you have fixed two bugs in one file but only want to stash one fix while committing the other. You can use the interactive, patch mode:

how to use stash git

git stash -p

Git will walk you through each “hunk” of changes and ask if you want to stash it. You can answer yes (y), no (n), or even split (s) a large hunk into smaller ones. This gives you surgical precision over what goes into the stash.

Cleaning Up Your Stash Stack

Stashes are not meant to be permanent storage. To delete a specific stash:

git stash drop stash@{3}

To clear your entire stash stack (use with caution):

git stash clear

Common Pitfalls and How to Avoid Them

Even with a great tool, mistakes happen. Here is how to navigate the most common stash-related issues.

Merge Conflicts on Apply or Pop

This is the most frequent hurdle. If you get conflicts, Git enters a merge state. You must resolve the conflicts manually in your files, then mark them as resolved. After resolving all conflicts, if you used `git stash pop`, you must manually complete the process with `git stash drop`. If you used `git stash apply`, the stash remains, and you can decide to drop it later after verifying the application was correct.

Forgetting to Include Untracked Files

The classic mistake: you stash, switch branches, and your new configuration file is gone. Remember, `git stash` alone ignores untracked files. Always use `git stash -u` if you have new files you need to preserve. For a safety habit, you can check your status with `git status` before stashing to see what is tracked and untracked.

Losing Track of Multiple Stashes

A stack of ten stashes with vague messages like “WIP” is useless. Always use descriptive messages with `-m`. Regularly review your list with `git stash list` and clean up old stashes you no longer need with `git stash drop`. Treat your stash stack like a temporary notepad, not an archive.

Integrating Stash into Your Daily Git Flow

Stash is not just for emergencies. Weave it into your standard workflow to stay clean and agile.

Use it before pulling updates. If you have local modifications and need to do a `git pull`, stash first to avoid a conflict during the fetch/merge: `git stash`, then `git pull`, then `git stash pop`.

Use it to test a clean build. Need to see if the current branch builds without your in-progress changes? `git stash -u`, run your build/test command, then `git stash pop` to restore your work.

Use it for quick context switches. As in the opening scenario, it is the official way to pause one task and start another without committing broken code.

Your Actionable Stash Workflow Checklist

To cement this knowledge, here is a step-by-step checklist for a typical scenario:

– You are on `feature/awesome` with uncommitted changes.
– Run `git status` to audit changes.
– Run `git stash push -u -m “Descriptive message”` to save everything.
– Verify a clean working directory with `git status`.
– Switch to the target branch: `git checkout main`.
– Do your urgent work, commit, and push.
– Return to your feature branch: `git checkout feature/awesome`.
– Restore your context: `git stash pop`.
– If conflicts arise, resolve them, then run `git stash drop` if needed.

By adopting these practices, you move from fearing context switches to managing them with confidence. The git stash command transforms your working directory from a fragile, single-threaded workspace into a multi-tasking environment. You can keep your commit history clean and meaningful while never losing valuable, in-progress work. Start using it today; it will quickly become one of the most relied-upon tools in your Git arsenal.

Leave a Comment

close