How to Git Stash a Specific File: A Step-by-Step Guide

In Git, stashing is a handy feature that allows you to temporarily set aside changes that you're not ready to commit. But what if you only want to stash changes made to a specific file or directory?

Since Git version 2.13, this process has become more straightforward. Here's a look at how to git stash a specific file or path, along with an alternative method for older versions.

Stashing a Specific File or Path (Git 2.13 and Later)

From Git 2.13 onwards, you can stash changes in a specific file or directory using the git stash push command followed by the path you want to stash. Here's an example:

git stash push -m "Description of Stash" app/views/cart/welcome.html

In this command:

  • -m "Description of Stash": Allows you to add a message to your stash for easy identification later.
  • app/views/cart/welcome.thtml: This is the path of the file or directory you want to stash.

This method is straightforward and efficient, especially when you need to stash changes in just one or a few files.

Stashing a Specific File Using the Patch Option (Older Versions)

Before Git 2.13, or for more granularity, you can use git stash --patch (or git stash -p for short). This method is a bit more manual but offers more control:

1. Start Stash in Patch Mode:

git stash --patch

This command starts an interactive session where Git presents each "hunk" (or section of changes) to you.

2. Interactive Stashing:

  • When presented with a hunk from a file you don't want to stash, press n to skip it.
  • Press y when you encounter a hunk from the file you wish to stash.
  • To stash the current hunk and all remaining hunks in the same file, press a.
  • Once you've stashed the necessary changes, press q to exit and leave the remaining hunks unstashed.

This interactive approach isn't the most intuitive, but it's a powerful tool when you need precise control over what you stash.

Subscribe to GIT.WTF!?!

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]