loading...

git stash in one minute

teoladmann profile image Timoteo Ladmann ・2 min read

Use case

You are working on {some-task}. Suddenly, you receive a message:

  • Hey {your-name}, we need you to urgently fix {some-urgent-task}.

You think ok, but what do I do with the current work in progress of {some-task}? You evaluate your options:

❌ commit the unfinished work: not good because maybe you don't have it working yet. Or maybe it is working, but you don't want to pollute the commit history.

❌ create a branch for the unfinished work: solves the issue of not pushing something that's broken (if that's the case), but you still have to commit unfinished work.

✅ use git stash: saves your current uncommitted changes for later use without the need to commit the unfinished work.

How to use it

1) Save your work in progress for later:

git stash save -u '{what-you-are-working-on}'
Enter fullscreen mode Exit fullscreen mode

The -u is to stash also new files that you've created in the current changes. The save is for giving a name to your current work in progress (useful for retrieving it later).

2) Work in the more urgent task.

3) Once you finish with the more urgent task and want to go back to your stashed work in progress you have two options. The first one is a shortcut to retrieving the last stash created:

git stash pop
Enter fullscreen mode Exit fullscreen mode

But it may happen that you have a list of stashes. In that case you first want to:

git stash list
Enter fullscreen mode Exit fullscreen mode

See what stash is the one that you want to retrieve to continue working on it (say, for example, number 3) and retrieve it:

git stash pop stash@{3}
Enter fullscreen mode Exit fullscreen mode

There are more things you can do with git stash. If you want to check it in more depth, I recommend reading Atlassian's tutorial on it.

Discussion

pic
Editor guide
Collapse
j23schoen profile image
Justin Schoen

one of my favorite little shortcuts it auto-stashing and popping, combined with rebasing on pull. I have this in my global gitconfig.
[rebase]
autoStash = true
[pull]
rebase = true

you can also do git pull -r --autostash
now, if you need to pull code but have changes in flight you don't need to stash, pull, then pop. you can do it all in one go

Collapse
awesomeironman profile image
Cyrus Gracias

There's also -p flag instead of -u which will help you stash files-code selectively
It opens a wizard of patching, where you tell git whether to stash a piece of code or not