Git is a powerful version control system that allows you to manage changes to your codebase. One of its most useful features is the ability to stash changes, which temporarily saves them away so you can work on something else. However, sometimes you may only want to stash specific files, leaving others unchanged. In this tutorial, we’ll explore how to do just that.
Understanding Git Stash
Before we dive into stashing specific files, let’s quickly review what git stash
does. When you run git stash
, Git saves the changes you’ve made to your working directory and index away in a temporary area, allowing you to switch to a different branch or commit without losing your work.
Stashing Specific Files
As of Git version 2.13, you can use the git stash push
command to stash specific files. The syntax is as follows:
git stash push -m "stash message" <path>
Replace <path>
with the file or directory you want to stash. For example, to stash a file named welcome.thtml
in the app/views/cart
directory, you would run:
git stash push -m "stash welcome.thtml" app/views/cart/welcome.thtml
This will save the changes to welcome.thtml
away in a new stash, leaving other files unchanged.
Stashing Multiple Files
If you want to stash multiple files at once, you can list them separately:
git stash push -m "stash message" file1.txt file2.txt
Alternatively, you can use a directory path to stash all changes within that directory:
git stash push -m "stash src directory" src/
Interactive Stashing (Git < 2.13)
If you’re using an earlier version of Git, you can use git stash --patch
(or git stash -p
) to interactively select which files to stash. When you run this command, Git will present each changed file (or "hunk") individually, allowing you to choose whether to stash it or not.
To stash a specific file using this method:
- Run
git stash --patch
- When prompted, type
n
to skip files you don’t want to stash - Type
y
when you encounter the file you want to stash - Type
q
to quit and leave remaining hunks unstashed
Alternative Approach: Staging Unwanted Changes
Another way to stash specific files is to stage the changes you don’t want to stash using git add
, then run git stash --keep-index
. This will save all unstaged changes away in a new stash, leaving staged changes intact.
For example:
git add app/controllers/cart_controller.php
git stash --keep-index
Note that this approach can lead to merge conflicts when you later pop the stash, so use with caution.
Conclusion
Stashing specific files with Git is a powerful technique for managing your workflow. By using git stash push
or interactive stashing, you can easily save away changes to individual files or directories, allowing you to focus on other tasks without losing your work.