Working with Git: use Stash to save your work
Git is one of the most popular version control tools used by developers to manage their code. One of its lesser-known but highly useful features is git stash. This feature allows developers to temporarily store changes without committing them. This article will explain what git stash is, when to use it, and how to use it effectively.
# What is Git Stash?
Git stash is a feature that enables you to save your working directory changes (both modified and newly added files) in a stash without affecting the branch you’re working on. In other words, it temporarily saves changes so you can work with a clean branch.
# When to Use Git Stash?
Git stash is particularly useful in the following scenarios:
- Switching Branches: You’re working on a feature, but you suddenly need to switch to another branch to fix a critical bug.
- Avoiding Premature Commits: You have incomplete changes and want to save them without making an unfinished commit.
- Testing Changes: You want to experiment with your code without altering the current branch state.
# How to Use Git Stash
Below are some basic commands for working with git stash:
# 1. Stashing Changes
Use the following command to stash your changes:
git stash
To include untracked files, use:
git stash -u
# 2. Viewing the Stash List
To view the list of all saved stashes, use:
git stash list
The output will display a list of stashes in the format:
stash@{0}: WIP on main: Update README.md
stash@{1}: WIP on feature: Add login functionality
# 3. Reapplying Stashed Changes
To reapply the most recent stash, use:
git stash apply
To remove the stash after applying it, use:
git stash pop
# 4. Deleting Stashes
To delete a specific stash, use:
git stash drop stash@{index}
For example:
git stash drop stash@{0}
To clear all stashes, use:
git stash clear
# Use Case Example
Scenario: You are working on the feature-a
branch and have made some changes. Suddenly, you are asked to switch to the main
branch to fix a bug.
Steps:
Stash your changes with git stash:
git stash
Switch to the
main
branch:git checkout main
After fixing the bug on the
main
branch, return to thefeature-a
branch:git checkout feature-a
Reapply your stashed changes:
git stash pop
# Conclusion
Git stash is an incredibly useful tool for managing temporary changes without disrupting your workflow. By understanding basic commands like git stash
, git stash apply
, and git stash pop
, you can work more flexibly when managing your code. This feature is one of the reasons why Git remains the top choice for developers worldwide.