How can I git stash a specific file?

ID : 494

viewed : 282

Tags : gitgit-stashgit





Top 5 Answer for How can I git stash a specific file?

vote vote

95

EDIT: Since git 2.13, there is a command to save a specific path to the stash: git stash push <path>. For example:

git stash push -m welcome_cart app/views/cart/welcome.thtml 

OLD ANSWER:

You can do that using git stash --patch (or git stash -p) -- you'll enter interactive mode where you'll be presented with each hunk that was changed. Use n to skip the files that you don't want to stash, y when you encounter the one that you want to stash, and q to quit and leave the remaining hunks unstashed. a will stash the shown hunk and the rest of the hunks in that file.

Not the most user-friendly approach, but it gets the work done if you really need it.

vote vote

89

I usually add to index changes I don't want to stash and then stash with --keep-index option.

git add app/controllers/cart_controller.php git stash --keep-index git reset 

The last step is optional, but usually, you want it. It removes changes from the index.


Warning As noted in the comments, git stash --keep-index pushes everything onto the stash, both staged and unstaged. The --keep-index just leaves the index alone after the stash is done. This can cause merge conflicts when you later pop the stash.

vote vote

71

To add to svick's answer, the -m option simply adds a message to your stash, and is entirely optional. Thus, the command

git stash push [paths you wish to stash] 

is perfectly valid. So for instance, if I want to only stash changes in the src/ directory, I can just run

git stash push src/ 
vote vote

66

If you are using visual studio code there is a simpler way to stash selected files.

  1. Go to Source Control tab
  2. Select files those you want to stash
  3. Right click on it, you will see many options. Click on Stash Changes

enter image description here

  1. Now it will ask you to add some stash message. Add understandable message and hit enter.

enter image description here

vote vote

57

For stashing one file:

git stash -- filename.txt 

For stashing more than one files:

git stash -- filename1.txt filename2.txt 

Top 3 video Explaining How can I git stash a specific file?







Related QUESTION?