How to use git stash

git stash stores (or stashes) changes you’ve made to your working copy so you can work on something else and then reapply them later. If you need to quickly switch context and work on something else, but you’re in the middle of a code change and aren’t ready to commit, stashing comes in handy.

Why is git stash important?

The first thing to grasp is the significance of Git stashing changes. Let’s pretend Git doesn’t have a command for stashing changes. Assume you’re working with a repository that has two branches, A and B. For a long time, the A and B branches have been separated and have different heads. Your team asks you to fix a bug in branch B while you’re working on some files in branch A. You quickly save your changes to branch A and use git checkout B to check out branch B. Git aborts the operation right away and throws an error.

Stash your Progress

Here’s the sequence to follow when using git stash:

  1. Save changes to branch A.
  2. Run git stash.
  3. Check out branch B.
  4. Fix the bug in branch B.
  5. Commit and (optionally) push to remote.
  6. Check out branch A
  7. Run git stash pop to get your stashed changes back.

Git stash saves your changes to the working directory locally (inside your project’s.git directory; specifically, /.git/refs/stash) and allows you to retrieve them when you need them. It comes in handy when switching between contexts. It allows you to save changes for later use and is the quickest way to clean up your working directory while keeping your changes intact.

How to create a stash

The simplest command to stash your changes is git stash:

$ git stash

Uncommitted changes (staged and unstaged files) are stored (or “stashes”) by default, while untracked and ignored files are ignored. You don’t usually need to keep untracked and ignored files, but they can sometimes get in the way of other things you want to do in your codebase.

Additional options can be used to have git stash handle untracked and ignored files:

  • git stash -u or git stash --include-untracked stash untracked files.
  • git stash -a or git stash --all stash untracked files and ignored files.

Apply your stash

You can reapply previously stashed changes with git stash pop:

  • git status
  • git stash pop

When you pop your stash, the changes are removed from your stash and reapplied to your working copy.

Now that you understand the basics of stashing, you should be aware of one caveat with git stash: by default, Git will not stash changes to untracked or ignored files.

Reference

Leave a Comment

Your email address will not be published. Required fields are marked *