How to save Git changes using Git stash

Sometimes we have been coding for a while and made quite a few changes to your source code but for some reason you need to checkout a different branch and you don’t want to commit the code changes you made.

That’s a great use case for the git stash command. Today I’ll list out some of the most useful ways to apply this command and the situation where to use it.

1 – git stash

What it does: it saves all your current work locally and adds a reference to those saves on a list.

When to use it: you can use git stash when you have code changes that you don’t want to commit but you also don’t want to lose it. You might want to checkout a different branch at that moment, so just use git stash to save your code and get back to it later.

2- git stash apply

What it does: it applies the latests stashed changes to your current project.

When to use it: you can use git stash apply when you have code stashed code that you now want to use again. One big difference between git stash apply and git stash pop is that git stash apply keeps the code you recovered saved in the stash, whereas git stash pop removes it.

3- git stash pop

What it does: it’s pretty much git stash apply that also removes the reference to the changes from the stash.

When to use it: whenever you would use git stash apply but at the same time you don’t want to keep the changes in your stash.

4-git stash list

What it does: it lists everything that is currently in your stash. Every time you do a git stash, the references to those code changes is saved and can be listed with the above command.

git stash output
git stash output. source

When to use it: you can use this command when you want to see what is in your stash or to help you see which of the stashed items you want to apply

5- git stash apply stash@{n}

What it does: it applies a specific stash item from your stash lis

When to use it: when you want to apply stashed code that isn’t the latests one on your stash list. Let’s say you stashed 10 items(code changes) over your development process and you need to get the third item you stashed, you would use git stash apply stash@{3}. You can also use the syntax with the pop command.

Those are the features of the git stash command that you will most likely need to know when navigating through your git repositories.

Another big part of working with git repositories is knowing how to merge code without having to constantly clone the project. That’s why I wrote this short guide on how to merge code on git in 7 easy steps.

I hope it helps you out.

Thanks for reading,

Gásten Sauzande.

Leave a Reply

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