git stash, to the rescue

Introduction

git, the version-control system we all use. It has helped save a tremendous number of work hours by simplifying the process to track changes in source code during software development. Today I will try to demystify one of its commands to help you save some more time.

Use cases

Let's be real, you often come across a situation where you are doing what you do best, writing some awesome code. But, suddenly you are required to just make your changes disappear and test some other code. Now, you are not ready to commit your changes yet. What do you do? The answer to this issue is the git stash command.

The git stash command takes your uncommitted changes (both staged and unstaged), saves them away for later use, and then reverts them from your working copy. For example:

Dirty state

$ git status
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

	modified:   index.html

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

	modified:   lib/simplegit.rb

Stashing the changes

$ git stash
Saved working directory and index state \
  "WIP on master: 049d078 Create index file"
HEAD is now at 049d078 Create index file

Clean state

$ git status
# On branch master
nothing to commit, working tree clean

You can reapply previously stashed changes with git stash pop.

$ git stash pop
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	modified:   index.html
	modified:   lib/simplegit.rb

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

Bonus tip, you can also stash untracked files using git stash --include-untracked.

© 2020 Brijesh Shah, Built with Gatsby