DEV Community

Cover image for Tip: Stashing selected files in git
Dzhavat Ushev
Dzhavat Ushev

Posted on • Originally published at dzhavat.github.io

Tip: Stashing selected files in git

One of my favorite git commands is git stash. I use it all the time. I like how it helps me clean my working directory but still save my work for later.

One downside of using git stash, though, is that it stashes away all files. What I need in some cases is to stash only a few selected files or a single directory. Iโ€™ve needed this in several occasions but never really tried to research it (yeah, call me lazy).

Until a couple of days ago - thatโ€™s how stories unfold - when I finally visited the official docs for stash! I found an option called <pathspec>. This option can be used with the push command to specify a path. Git will then stash all files that match the path.

How does it look in practice? Say I have the following files in my working directory:

js/custom.js
css/custom.css
Enter fullscreen mode Exit fullscreen mode

Here are a few use cases I might have:

# to stash just the `custom.js` file
git stash push js/custom.js

# to stash the `custom.js` file with a custom message
git stash push js/custom.js -m "Best feature ever"

# to stash only the files in the `js` directory
git stash push js/
Enter fullscreen mode Exit fullscreen mode

Iโ€™m quite happy about discovering this. Iโ€™ll definitely use it in my work. Hope you learned something new today as well. ๐Ÿ˜‰

P.S. Iโ€™ve created a Git Cheatsheet extension for VS Code that can help you with remembering some common git commands.

Top comments (0)