Practical Guide to GIT Stash


Git stash is a command that temporarily stores changes made to a working tree so that they can be reapplied later. Git stash is useful when you need to switch to another branch or perform some other operation that requires a clean working directory, but you are not ready to commit your changes. You can later unstash your changes and continue working on them.

To unstash changes, use the git stash apply command. This command applies the most recent stash to the working directory.

Here’s an example of how to use git stash and git stash apply:

  1. Make some changes to a file in your working directory:
$ echo "Hello, world" > file.txt
  1. Stash the changes using the git stash command:
$ git stash
Saved working directory and index state WIP on master: 95c44f3 Add new feature
  1. Switch to a different branch:
$ git checkout other-branch
  1. Now, let’s say you want to apply the changes you stashed earlier. You can use the git stash apply command to do this:
$ git stash apply

This will apply the most recent stash to your working directory. If there are no conflicts, your changes will be restored.

  1. If you have multiple stashes, you can specify which stash you want to apply using its stash ID. You can view the list of all stashes by running:
$ git stash list
stash@{0}: WIP on master: 95c44f3 Add new feature
stash@{1}: WIP on master: 4c0fe78 Fix bug

To apply a specific stash, use the git stash apply command followed by the stash ID. For example, to apply the stash with ID stash@{1}, run:

$ git stash apply stash@{1}

This will apply the stash with ID stash@{1} to your working directory.

  1. If you want to remove the stashed changes after applying them, you can use the git stash drop command. For example:
$ git stash drop stash@{1}

This will remove the stash with ID stash@{1}.

Example:

Suppose you are working on a feature branch featureA, and you made some changes to a file and then stashed them using the command git stash. You then switched to another branch featureB to work on a different feature. Later, you realized that you need the changes you made in featureA. You can unstash the changes and apply them to the featureB branch using the following commands:

$ git stash apply

This will apply the most recent stash to your working directory. If there are no conflicts, your changes will be restored.

Alternatively, if you have multiple stashes and want to apply a specific stash, you can use the stash ID. For example, if you want to apply the stash with ID stash@{0}, you can use the following command:

$ git stash apply stash@{0}

Once the stash is applied, you can continue working on the featureB branch. If you want to remove the stashed changes from the featureA branch, you can use the git stash drop command as follows:

$ git stash drop stash@{0}