How to use GIT stash

git stash is one of those less-known commands that can be real life saver.

In this article I will explain what it is, why you should use it and some scenarios when it should be used.

So let’s get right down to it!

Table of contents:

  • Why to use git stash
  • How to use git stash

Why to use git stash

This is a great question you might ask. The command git stash is a great way how to temporarily clear your working directory, if you need to switch branches without a need to commit unfinished work or when you need to pull the newest changes into your local branch.

How to use git stash

git stash is a command that saves the modified files in your repository into some “cache” and subsequently clears all modified files.

For example after using git status you might get this:

$ git status
 Changes to be committed:
   (use "git reset HEAD …" to unstage)
 modified:   index.html
 
Changes not staged for commit:
   (use "git add …" to update what will be committed)
   (use "git checkout -- …" to discard changes in working directory)
 modified:   lib/script.js

Untracked files:
   (use "git add …" to include in what will be committed)
     404.html

Now, after using git stash you will get this:

On branch master
 Your branch is up to date with 'origin/master'.

 Untracked files:
   (use "git add …" to include in what will be committed)
     index.html

What has happened there?

Well, all of your changes somehow disappeared and the untracked files stayed.

That is exactly what git stash does.

How to get my changes back?

It’s pretty straightforward. You will get your stashed changes back by using a command git stash apply.

There is also an alternative command you might find called git stash pop – which I don’t recommend using on your habitual basis.

The difference between git stash apply and git stash pop is that while git stash apply get your changes back, git stash pop does get your changes back, but it will remove them from the local cache and once applied, they are lost forever.

Wrap up

I hope this article provided some light on the very simple command git stash. You might not use it every day, but when you do, you will be thankful you§d learnt it beforehand.

You can check out some more tutorial on GIT here.

Until then,

Yours in coding,

Ivan

Sources:

Credits:

Leave a comment

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