The git stash
command in Git is used to temporarily save changes in your working directory that are not ready to be committed. This allows you to switch branches, pull updates, or perform other tasks without losing your work. Below is a detailed explanation of the purpose of git stash
, along with sample commands.
1. Why Use Git Stash?
The git stash
command is useful in the following scenarios:
- Switching Branches: You have uncommitted changes but need to switch to another branch.
- Pulling Updates: You want to pull the latest changes from a remote repository but have uncommitted work.
- Temporary Storage: You need to temporarily save changes to work on something else.
2. Basic Git Stash Commands
Here are the basic commands for using git stash
:
Stashing Changes
To stash your current changes, use the following command:
git stash
This command saves your changes in a stash and reverts your working directory to the last commit.
Listing Stashes
To view a list of all stashes, use:
git stash list
This command displays a list of stashes with unique identifiers (e.g., stash@{0}
).
Applying Stashed Changes
To apply the most recent stash and remove it from the stash list, use:
git stash pop
To apply a specific stash, use:
git stash apply stash@{n}
Replace n
with the index of the stash you want to apply.
Dropping Stashes
To remove a specific stash from the stash list without applying it, use:
git stash drop stash@{n}
To remove all stashes, use:
git stash clear
3. Stashing Untracked Files
By default, git stash
only stashes tracked files. To include untracked files, use the -u
or --include-untracked
flag:
git stash -u
4. Stashing with a Message
To add a descriptive message to your stash, use the save
command:
git stash save "Your descriptive message"
This helps you identify the purpose of the stash when viewing the stash list.
5. Example Workflow
Here’s an example workflow for using git stash
:
# Make changes to your working directory
git add .
git stash
# Switch to another branch
git checkout other-branch
# Perform tasks on the other branch
git checkout main
# Apply the stashed changes
git stash pop
6. Best Practices for Using Git Stash
To use git stash
effectively, consider the following best practices:
- Use Descriptive Messages: Add messages to your stashes to make them easier to identify.
- Review Stashes Regularly: Periodically review and clean up your stash list to avoid clutter.
- Commit When Ready: Use stashes for temporary storage and commit your changes when they are ready.
7. Conclusion
The git stash
command is a powerful tool for managing uncommitted changes in your working directory. It allows you to temporarily save your work, switch contexts, and return to your changes later without losing any progress. By understanding how to use git stash
effectively, you can maintain a clean workflow and handle interruptions with ease.