Sunday 3 January 2016

Git - Stashing

Stash

Stash is a place where we can store changes temporarily without committing them to the repository. This is the special 4th area in Git (other 3 are - Working directory, Staging Index and Repository). Stash are like commits with snapshot of changes but no SHA-1 associated.

Use Cases

1] Git doesn't allow you to switch branch if the working directory is not clean. But I want to switch branch - The solution is Stashing.

2] I am doing some development on a branch and realized that I am on incorrect branch. These all uncommitted changes (working or staging) need be moved to a different branch - The solution is Stashing.


Let's see Stashing in action !

Creating Stash

To create a stash from all changes in working directory,
$ git stash save "Message here for your benefit"

E.g. I edited two files header.html and index.html on website branch. Added header.html to staging and then created stash.

$ git status -s
M  header.html
 M index.html

$ git stash save "Changes in index.html & header.html"

Once it creates stash it executes $ git reset --hard HEAD command & HEAD points to last commit.

View Stash changes

To list all the stashes created,
$ git stash list
stash@{0}: On website: Changes in index.html & header.html

The representation format of stash is 
stash@{<number>}: On <branch_name_on_stash_created>:message

We can refer to a stash by stash@{<number>}

To view changes in a stash, 
$ git stash show stash@{0}
 header.html | 1 +
 index.html  | 1 +
 2 files changed, 2 insertions(+)

To get details about changes, use patch flag (-p)
$ git stash show -p stash@{0}

Pulling Stash Changes

There are two approaches to pull stash changes into present working directory.
1. pop -  (used often) This will pull stashed changes into current working directory and delete stash entry.

$ git stash pop stash@{<number>}

2. apply - This will pull stashed changes into current working directory but will not delete the stash.

$ git stash apply stash@{<number>}

You can pull these changes in the working directory of a different branch too (Refer: Use Case - 2).

Deleting Stash

To delete a particular stash,
$ git stash drop stash@{<number>}

To remove all the stashes,
$ git stash clear

No comments:

Post a Comment

Your comments are very much valuable for us. Thanks for giving your precious time.

Do you like this article?