Working with Stash

Scenarios

Let's consider a scenario where you are working on a feature branch in your Git repository. You have made some changes to the code but haven't completed the task yet. Suddenly, you receive an urgent bug report from a user that requires your immediate attention. You need to switch to the master branch to fix the bug, but you don't want to lose your current changes on the feature branch.

To save your changes in a stash, you can use the git stash save command. Let's assume you are on the feature branch, and you want to stash your modifications:

git stash save "My work in progress"

The "My work in progress" is an optional message that you can provide to describe the stash. It helps you identify the stash later when you have multiple stashes.

After executing the command, Git will create a new stash containing your modifications and revert your working directory to the last commit. You can now safely switch to the master branch or perform any other actions.

Listing Stashes with git stash list

To see the list of stashes you have created, you can use the git stash list command. It will display the stash index, message, and the branch where the stash was created. Here's an example:

git stash list

output:

stash@{0}: On feature-branch: My work in progress
stash@{1}: On another-branch: Fixing some bugs

In this example, there are two stashes available. The most recent stash (stash@{0}) was created on the feature-branch, and the message associated with it is "My work in progress." The second stash (stash@{1}) was created on another-branch with the message "Fixing some bugs."

Applying a Stash with git stash apply

Once you are ready to continue working on your changes, you can apply the stash back to your working directory using the git stash apply command. By default, this command applies the most recent stash. If you have multiple stashes and want to apply a specific one, you can provide its index as an argument.

git stash apply

This command applies the most recent stash and brings back your changes to the working directory. If you have multiple stashes and want to apply a specific one, you can use the stash index:

git stash apply stash@{1}

The apply command doesn't remove the stash after applying it. If you want to remove the stash from the stash list, you can use the git stash drop command:

git stash drop stash@{1}

Remember to replace stash@{1} with the appropriate stash index.

Working with Git stash provides a convenient way to temporarily save your changes without committing them to the repository

Last updated