DEV Community

Cover image for How to stash a specific file or multiple files?
Yashu Mittal
Yashu Mittal

Posted on

git stash specific files How to stash a specific file or multiple files?

How to stash a specific file or multiple files?

Top comments (11)

Collapse
 
gianpaj profile image
Gianfranco P. • • Edited

This didn't work:
git stash _file_
This did:
git stash push _file_ --keep-index

$ git stash src/services/styles.ts
fatal: unknown subcommand: src/services/styles.ts

...
Enter fullscreen mode Exit fullscreen mode
git stash push src/services/styles.ts --keep-index
Saved working directory and index state WIP on _branch_name_: 32dbc82 ....
Enter fullscreen mode Exit fullscreen mode
$  git --version
git version 2.28.
Enter fullscreen mode Exit fullscreen mode
Collapse
 
deciduously profile image
Ben Lovy •

git stash - e.g. git stash . or git stash src/index.js. Then git stash apply to apply the stashed changes or git stash drop to discard them.

Is that what you're looking for?

Collapse
 
ryzngard profile image
Andrew Hall •

git stash pop is like apply + drop as well. I think git stash --keep-index keeps everything staged, and stashes unstaged changes. Useful if it's hard to type the pathspec for multiple files, or if you want to stash some changes to a file but not all.

Collapse
 
andy profile image
Andy Zhao (he/him) •

Big fan of git stash pop. Definitely a 1 command > 2 commands scenario.

Thread Thread
 
deciduously profile image
Ben Lovy •

Whoa, TIL. Git's pretty cool, isn't it

Collapse
 
mittalyashu profile image
Yashu Mittal •

Yup. Cool 😎

What does -p -u flag does?

Collapse
 
chhajedji profile image
chinmay chhajed •

git stash --keep-index it is.

Add the changes to the staging area which you do not want to stash. All changes to be stashed should be not staged but modified or untracked. Then you can just git stash --keep-index to stash changes. As mentioned in some other answer, add -u to add untracked files also. Then you can just git restore --staged <file names> to bring staged changes back to modified.

Collapse
 
ejrojasb profile image
EmilioJRB •

I suggest git stash save "a comment here". I always use it, it is the best way or working with stashes, the indexes may get you lost

Collapse
 
iamsteveworsley profile image
Steve Worsley •

Just to help people coming from google the save command has been deprecated:

This option is deprecated in favour of git stash push. It differs from "stash push" in that it cannot take pathspecs, and any non-option arguments form the message.