git stash command can sometimes seem to have a mind of its own, but it's fairly easy to use (and extremely useful) once you familiarise yourself with the nuances of how it works.
In this guide, we look at how to stash single (or multiple) specific files while letting your other files be ignored.
Related: How to delete git branches
Method 1: Using the file path
With the newer versions of git, you can git stash one file using the command:
$ git stash push <path>
Here, <path> specifies the path of the file you want to stash. For example, if you want to stash a file called
admin.js that lives in the src directory, you would use the following command:
$ git stash push src/admin
If instead, you wanted to stash everything in the src directory, you would use the command:
$ git stash push src/
Method 2: Using the
In the olden days, the way to stash a single file was a bit more cumbersome, but we will guide you through it anyway because it still works!
You can use the
git stash --patch (or
git stash -p) command. This would put you in git's interactive mode. Patch lets you one by one select each hunk that has changed (including files) that you want to be stashed.
Here, you will be given where you'll be presented with each hunk that was changed. You will also be given a bunch of options to choose what you would like to do with that hunk. These include:
When going through interactive mode, use
n to skip the files you don't wish to stash and press
y for when you see a file that you want to include in your stash.
And that's how you do it. Hopefully, with this guide, you will find it easier to stash single file entries (or even chunks of code)!