← til

Git stash is awesome

January 16, 2012
git

I really like git stash command. It lets you save your current progress and rollback the head state to the last commit.

Let's say this is my current situation:

$ git status

# On branch master
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified:   Gemfile.lock
# modified:   Rakefile
# modified:   _config.yml
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
# sass/
# source/
no changes added to commit (use "git add" and/or "git commit -a")

We're going to save everything into stash.

$ git add .
$ git stash save
$ git status

# On branch source
nothing to commit (working directory clean)

So it basically cleaned up the working directory. This comes very handy when you have to fix something on your last commit, but you already made some progress on the other part of your application. With this command you basically put your changes elsewhere and you're able to commit that fix.

After the ordinary git add -A && git commit && git push command flow, you can issue git stash list. This shows you the current stash status.

You can have multiple items in your stash, and when you do it's very handy to mark them with messages like this:

git stash save "started to work on task 3.2"

So let's say you got multiple items in your stash:

$ git stash list

stash@{0}: WIP on master: e106412 test fix and price display fix
stash@{1}: On master: fixing humanized attributes

If you execute git stash apply now, the last added item will be pulled out of the stash and merged with master (stashes really follow LIFO principle). We can still merge an item named “fixing humanized attributes” like this:

$ git stash apply stash@{1}.

This is not the only scenario where stash comes handy. It also does when you wish to switch branches, rollback states, but would like to keep your current changes.

It's also nice to clean up your stash regularly so you don't get lost in too many items. You can do that with git stash clear, but be careful with it since it doesn't ask you to confirm your little stashocide.