Stashing Changes
Now that we have our workspace set up, let's create some changes and learn how to stash them.
First, let's make some changes to our README.md file:
echo "This is a work in progress" >> README.md
This command appends a new line to our README.md file. Let's also create a new file:
echo "Some important notes" > notes.txt
Now, if we run git status
, we'll see that we have both modified and untracked files:
git status
You should see output indicating that README.md is modified and notes.txt is untracked.
Imagine at this point you need to quickly switch to a different task, but you're not ready to commit these changes. This is where git stash
comes in handy!
To stash your changes, run:
git stash
You should see output similar to this:
Saved working directory and index state WIP on master: 1234567 Initial commit
Now, if you run git status
again, you'll see something interesting:
git status
You'll notice that while README.md is no longer shown as modified, notes.txt is still listed as an untracked file. This is a crucial point about git stash
:
Important: By default, git stash
only stashes:
- Changes to tracked files (files that Git is already tracking)
- Staged changes
Untracked files (like our notes.txt) are not included in the stash by default. This behavior ensures that Git doesn't accidentally hide new files you might not want to include in the repository.
If you want to include untracked files in your stash, you can use the -u
(or --include-untracked
) option:
git stash -u
After running this command, both the changes to README.md and the new notes.txt file will be stashed.
To see what's in your stash, you can use:
git stash list
You should see one or two stash entries, depending on whether you used the -u
option.
Press q
to exit the stash list view.
Remember, stashing is perfect for quick context switches. However, it's not a replacement for commits in your long-term workflow. Stashes are meant to be temporary storage.