Skip to main content

Getting started with Git stash

Posted in Development and Git

Normally, switching branches when there are some uncommitted changes is fine; the modified files just follow me when I checkout another branch. But sometimes I get this:

error: Your local changes to the following files would be overwritten by checkout:
src/site/_layouts/home.html
Please commit your changes or stash them before you switch branches.
Aborting

I’ve always been a bit scared of git stash since I started using Git on the command line. It was easy in Tower, where it nice and visual, so I’ve been doing naughty stuff like:

  1. copying the file
  2. undoing the changes
  3. switching branches, error-free
  4. pasting or redoing the changes back in

Aside from being mistake-prone and messy, sometimes that method is just not possible, like when I’ve used Patch mode where the most recent changes to the file might already have been committed, so undoing changes doesn’t undo the right stuff.

Stashing

Git stash gives us a place to store those git checkout-preventing changes so we can switch branch then apply them somewhere else.

git stash

That takes everything you’ve changed and makes a ‘stash’ with it.

But it doesn’t stash anything new, so if you have any untracked files, they won’t be stashed. To include untracked files in your stash, add the --include-untracked flag; luckily there’s a shorthand:

git stash -u

Applying the stash

Once you’ve moved to the branch you want to be on, just use:

git stash pop

This takes the changes out of your stash and applies them to the new branch; nothing is staged or committed.

At its most basic, it’s as simple as that. There’s a lot more you can do with git stash, but to move from branch to branch without any errors, or move some work out of the way to tackle something else, that’s all that’s needed. Not as scary as I’d thought!

Accessibility in your inbox

I send an accessibility-centric newsletter on the last day of every month, containing:

  • A roundup of the articles I’ve posted
  • A hot pick from my archives
  • Some interesting posts from around the web

I don’t collect any data on when, where or if people open the emails I send them. Your email will only be used to send you newsletters and will never be passed on. You can unsubscribe at any time.

More posts

Here are a couple more posts for you to enjoy. If that’s not enough, have a look at the full list.

  1. Upgrading from iPhone 13 mini to 16 Pro

    I get a new phone every 3-ish years, give mine to my wife, and now she gives hers to our daughter. I got a 16 Pro this year! Here’s the skinny.

  2. Apple, you’re doing the Dynamic Island wrong

    I love the idea of Dynamic Island; making lemons into lemonade and all that. But, in my opinion, Apple have got the fundamentals mixed up.