Mastering Stash: The Ultimate Guide for Beginners
Git Stash is one of Git’s most powerful, yet often misunderstood, features. It allows you to temporarily shelve (or stash) changes you’ve made to your working directory, leaving a clean working directory without committing incomplete work. This is incredibly useful in various scenarios, making it a crucial tool in any developer’s workflow. This guide will demystify git stash
for beginners, covering its core concepts, practical applications, and potential pitfalls.
1. What is Git Stash and Why Should You Use It?
Imagine you’re working on a new feature (let’s call it feature-a
), and you’ve made significant changes to several files. Suddenly, you’re asked to fix a critical bug on a different branch (bugfix
). You don’t want to commit your unfinished feature-a
work, as it’s not ready and might break things. This is where git stash
comes to the rescue.
git stash
essentially takes a snapshot of your modified and staged changes (but not untracked files by default – we’ll cover that later) and saves them in a special “stash stack.” This stack is a LIFO (Last In, First Out) queue, meaning the most recently stashed changes are the first to be retrieved. Your working directory is then reverted to the state of the last commit (the HEAD).
Why use git stash
?
- Switching branches with uncommitted changes: The most common use case. You can safely switch to another branch without losing your work or creating a messy commit history with half-finished features.
- Pulling changes with uncommitted work: If you have local changes that conflict with changes you’re trying to pull from a remote repository, you can stash your changes, pull, and then reapply your stashed work, resolving any conflicts.
- Temporarily removing changes for testing: You might want to test your code without certain modifications. Stashing allows you to quickly revert to a clean state, run your tests, and then reapply your changes.
- Experimenting without committing: You can stash a set of changes as a “save point” while you explore different approaches, knowing you can easily revert if needed.
2. Basic Stash Commands: A Step-by-Step Guide
Let’s dive into the core commands:
-
git stash push
(or the oldergit stash save
): This is your primary stashing command.bash
git stash push -m "Work on feature-a, part 1"-m "Your message"
: It’s highly recommended to always include a message. This makes it much easier to identify what’s in each stash later. Without a message, you’ll just see generic “WIP on branch_name” entries.- Without
-m
:git stash push
(orgit stash
) will stash your changes with a default message.
-
git stash list
: View your stash stack.bash
git stash listThis will output something like:
stash@{0}: On main: Work on feature-a, part 1
stash@{1}: WIP on main: Auto-stashed changes before rebase
stash@{2}: On feature-x: Implemented basic loginEach stash entry is identified by an index (e.g.,
stash@{0}
). The most recent stash is always at the top (stash@{0}
). -
git stash apply
: Reapplies the most recent stash (stash@{0}
) to your working directory. Crucially,apply
does not remove the stash from the stack.bash
git stash apply-
Apply a specific stash: You can apply a specific stash by its index:
bash
git stash apply stash@{2} # Applies the third stash in the list
-
-
git stash pop
: Reapplies the most recent stash and removes it from the stack. This is a combination ofgit stash apply
andgit stash drop
.bash
git stash pop- Pop a specific stash (and remove it): This is not recommended, as it makes it easy to accidentally drop the wrong stash. It is safer to
apply
and thendrop
- Pop a specific stash (and remove it): This is not recommended, as it makes it easy to accidentally drop the wrong stash. It is safer to
-
git stash drop
: Removes a stash from the stack. Be careful! This is permanent.bash
git stash drop stash@{0} # Drops the most recent stash
git stash drop stash@{1} # Drops second stash
It is safer toapply
first so you can test and see it is the right one. -
git stash clear
: Removes all stashes from the stack. Use with extreme caution!bash
git stash clear
3. Handling Untracked and Ignored Files
By default, git stash
only stashes tracked files (files that have been added to Git’s index with git add
). It ignores untracked files (new files that haven’t been added) and files listed in your .gitignore
file. Here’s how to handle these:
-
Stashing Untracked Files:
“`bash
git stash push -u -m “Including untracked files”OR, the long form:
git stash push –include-untracked -m “Including untracked files”
“`The
-u
(or--include-untracked
) option tells Git to also stash untracked files. -
Stashing Everything (Including Ignored Files):
“`bash
git stash push -a -m “Stashing everything, even ignored files”OR, the long form:
git stash push –all -m “Stashing everything, even ignored files”
“`The
-a
(or--all
) option stashes everything, including untracked files and files that are normally ignored by.gitignore
. Use this with caution, as you might accidentally stash build artifacts or other unwanted files.
4. Stashing Specific Files or Parts of Files
Sometimes, you only want to stash changes to specific files or even specific parts of files. Here’s how:
-
Stashing Specific Files:
bash
git stash push -m "Changes to file1 and file2" -- file1.txt file2.txtThe
--
is important. It separates thegit stash
options from the file paths. Everything after--
is treated as a file path. -
Stashing parts of a file with
git stash push -p
:
bash
git stash push -p #or
git stash push --patch
The-p
option allows for selectively stashing portions of files. The git stash command, with the -p option, will iterate through each “hunk” (change) in your modified files. For each hunk, you’ll be presented with a prompt and several options, allowing you to decide what to do with that specific change. Here’s a breakdown of the prompt and options:
The Prompt
After running git stash push -p, Git will display a hunk of changes, similar to what you see with git diff, along with a prompt like this:
Stash this hunk [y,n,q,a,d,/,j,J,g,e,?]?
Options Explained
* y: Yes, stash this hunk.
* n: No, do not stash this hunk.
* q: Quit; do not stash this hunk or any of the remaining hunks.
* a: Stash this hunk and all later hunks in the file.
* d: Do not stash this hunk or any of the later hunks in the file.
* /: Search for a hunk by a given string or regular expression.
* j: Leave this hunk undecided, see next undecided hunk.
* J: Leave this hunk undecided, see next hunk.
* g: Select a hunk to go to.
* e: Manually edit the current hunk.
* ?: Print help.
* s: Split the current hunk into smaller hunks.
* K: Leave this hunk undecided, see previous hunk.
* k: Leave this hunk undecided, see previous undecided hunk.
5. Branching from a Stash
If you decide that the work you stashed should become a new branch, you can create a branch directly from a stash:
bash
git stash branch <new-branch-name> stash@{2}
This command does the following:
- Creates a new branch named
<new-branch-name>
starting from the commit that was HEAD when the stash was created. - Applies the specified stash (
stash@{2}
in this example) to the new branch. - Removes the stash from the stash stack (like
git stash pop
).
If you don’t specify a stash, it defaults to the most recent one (stash@{0}
).
6. Resolving Conflicts After Stashing
When you apply
or pop
a stash, you might encounter conflicts, just like when merging branches. Git will mark the conflicting sections in your files with the usual conflict markers (<<<<<<<
, =======
, >>>>>>>
). You’ll need to:
- Manually resolve the conflicts: Edit the files to decide which changes to keep or how to combine them.
- Stage the resolved files: Use
git add
on the files you’ve resolved. - Commit (if necessary): If you were working on a branch when you stashed, you might need to commit the resolved changes. If you created a branch from the stash, you’ll definitely need to commit.
7. Common Mistakes and How to Avoid Them
- Forgetting to add a message: Always use
-m
to add a descriptive message. This will save you a lot of time and confusion later. - Accidentally dropping the wrong stash: Use
git stash list
to carefully check the stash index before usinggit stash drop
. Consider usinggit stash apply
first to test, thengit stash drop
if everything is correct. - Stashing large binary files: Stashing is generally best for code changes. Stashing large binary files can bloat your
.git
directory and slow things down. - Not stashing untracked files when needed: Remember the
-u
option if you need to stash new files. - Using
git stash pop
indiscriminately: While convenient,git stash pop
combines apply and drop. If there are conflicts, and you haven’t fully resolved them, popping the stash can make things more complicated. It’s often safer toapply
and thendrop
separately. git stash clear
without backing up: There is no “undo” forgit stash clear
. Be absolutely certain you don’t need any of your stashed changes before using it.
8. Advanced Stashing Techniques
- Partial stashes with interactive staging (advanced): As explained earlier.
9. Conclusion
git stash
is an indispensable tool for managing uncommitted changes in Git. By understanding its core concepts and commands, you can significantly improve your workflow, handle interruptions gracefully, and keep your commit history clean. Start with the basic commands, practice using messages, and gradually explore the more advanced options. Mastering git stash
will make you a more efficient and confident Git user.