What is the purpose of Git Stash command ?

In this sneppet you will learn what is Git Stash command and the when to use git stash command.

Git Stash Command

Use git stash command when you wanted to save the current state of your working directory and the index but wanted to go back to a clean working directory.

This command saves your local repository changes away and reverts the working directory to match the HEAD commit.

Git Stash Use Case

Let’s say your current working directory is messed up with the changes you made in your branch. But still you wanted to record the current state of your working directory before you pull changes using “git pull” command from the Git remote repository.

$ git stash

Saved working directory and index state WIP on main: ef8115c Merge branch 'main' of https://github.com/sneppets/gitdemo

The local changes that are stashed away by this command can be listed with “git stash list” command, inspected with “git stash show” command.

$ git stash list

stash@{0}: WIP on main: ef8115c Merge branch 'main' of https://github.com/sneppets/gitdemo
$ git stash show

 file1.txt | 1 +

 1 file changed, 1 insertion(+) 

If you want to pull latest changes from git run git pull

Now, run “git pull” command. Since you had stashed your local changes you should not see any conflict and could see your local branch is already up to date.

$ git pull

Already up to date

 and restored (potentially on top of a different commit) with git stash apply.

Please note, you also see a message output saying “restored with git stash apply”. Now you can restore stashed changes to your local branch.

$ git stash apply

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

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   file1.txt

no changes added to commit (use "git add" and/or "git commit -a")

Once you restore the changes, you can add the modifications using “git add” command and commit the changes using “git commit” command.

$ git add .
$ git commit -m "new changes in local"

[main 5204209] new changes in local

Finally, run “git push” command to push the changes to remote repository.

You can also check another use case which I explained in previous tutorial “Usage of git stash command while creating new branch from a tag in Git“.

Hope you find this sneppet useful 🙂

You’ll Also Like

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments