How to Stash Only Staged Changes in Git
• 1 min read
Normally, when I need to stash my code changes, I run git stash. This command stashes all my changes in the Git staging area. Then, I manage my stashes (pop, apply, drop) using Sublime Merge. I am pretty comfortable with this workflow.
However, while working on a task recently, I needed to quickly switch branches to check an issue for a colleague. Normally, I would run git stash before changing branches, but this time I didn't want to stash all the changes in the staging area. Instead, I wanted to stash only the staged files and leave the unstaged files as they were.
Luckily, there's a command for this:
git stash -- $(git diff --staged --name-only)Let's break it down:
git diff --staged --name-onlyoutputs a list of files with changes in the staging areagit stash -- $()stashes only the files listed by the previous command.- This ensures that only the staged changes are stashed, while any unstaged changes remain in the staging area.
Pretty neat, right? I hope this tip helps!