This tutorial aims to provide an in-depth understanding of using Git Stash for temporarily storing changes that you're not ready to commit.
By the end of this tutorial, you will learn:
Prerequisites:
git stash
is a command that takes your modified tracked files, stages changes, and saves them on a stack of unfinished changes that you can reapply at any time. This is particularly useful when you want to switch branches, but you're working on something that you're not ready to commit yet.
To stash your changes, use the following command:
git stash
This will take your uncommitted changes (both staged and unstaged), save them away for later use, and then revert them from your working directory.
You can list your stashed changes using:
git stash list
This will display all the stashed changes.
To apply the most recently stashed changes, use:
git stash apply
If you want to apply a specific stash, use:
git stash apply stash@{n}
Replace n
with the stash number.
Let's say you're working on your project and have made some changes, but you want to switch to another branch. Here's how you can use git stash
.
# You're working on your project and made some changes
echo "temp work" > temp.txt
git add temp.txt
# Save changes with git stash
git stash save "Work in progress for new feature"
In this example, a new file temp.txt
is created and added to Git. These changes are then stashed with a message "Work in progress for new feature".
# List all stashed changes
git stash list
This command will list all the stashed changes. The output might look something like: stash@{0}: On master: Work in progress for new feature
# Apply the most recent stash
git stash apply
# Or apply a specific stash
git stash apply stash@{0}
These commands will apply the stashed changes to your current working directory. The first one applies the most recent stash, while the second one applies a specific stash.
In this tutorial, we've covered:
git stash
to save uncommitted changes.git stash list
.git stash apply
.Next, you can learn about more specific git stash commands, like dropping a stash, creating a branch from a stash, etc.
Exercise 1: Make some changes in your git repository, stash them, and list your stashes.
Exercise 2: Apply the most recent stash you've created, then verify it has been applied correctly.
Exercise 3: Create multiple stashes, apply a specific stash, and drop a stash.
Solutions:
git stash save "Your message"
to stash changes and git stash list
to list stashes.git stash apply
to apply the most recent stash. You can verify it by checking your working directory.git stash apply stash@{n}
. Drop a stash with git stash drop stash@{n}
.Tips for further practice:
Try using git stash pop
, git stash branch
, and git stash clear
commands and understand their use cases.