Pages

Sunday, March 3, 2019

Git - Stashing

Lets say that we are implementing a new feature for the product. We have written some code and suddenly we need to make some changes to master repo. At this moment with half written code, we cannot commit the changes or throw away the code. We need a place where we can save our half written code and restore when we want to work on that again.

Stash operation in git helps us in doing so. The stash take your modified tracked files, stages changes and saves them on a stack of unfinished changes that we can re-apply any time.

Lets create a few files and see how stash works.
[root@test-machine project]# touch three four

[root@test-machine project]# git status -s
?? four
?? three

[root@test-machine project]# vi three

[root@test-machine project]# git add three

[root@test-machine project]# git status -s
AM  three
?? four

Now that we see there are few files that are added and modified, we don't want these changes to be committed or deleted. So we stash them as below,
[root@test-machine project]# git stash
Saved working directory and index state WIP on master: a1bfd95 changed comments
 by amend command
HEAD is now at a1bfd95 changed comments by amend command

The modified changes will not be moved to a stash location ( temp location ). Now if we see the “git status -s” again,
[root@test-machine project]# git status -s
?? four

We don't see the modified files. Lets see the list of stash available using,
[root@test-machine project]# git stash list
stash@{0}: WIP on master: a1bfd95 changed comments by amend command

In order to get back to the changes that are available on the stash, all we need to do is,
[root@test-machine project]# git stash pop
# On branch master
# Changes to be committed:
#   (use "git reset HEAD ..." to unstage)
#
#    new file:   three
#
# Untracked files:
#   (use "git add ..." to include in what will be committed)
#
#    four
Dropped refs/stash@{0} (e49d4f30fb8ad652059017dea2d4126dadaf44fb)

This will get back the top stash on the stack which is our last one. Now if we check the changes we can see,
[root@test-machine project]# git status -s
A  three
?? four
This way we can save our temporary changes and keep them aside to do our work.

No comments :

Post a Comment