2

I want to stash some files, and among those files, there are files which I want to stash completely and others which I want to stash part of them.

For example, let's say I have the files below:

  1. new_file_untracked_to_stash.txt
  2. new_file_untracked_not_to_stash.txt
  3. part_of_file_changes_to_stash.txt
  4. all_changes_to_stash.txt

The first 2 files (1 and 2) are new files, untracked. The 2 other (3 and 4) are tracked, one of them (3) has few lines that I want to stash and few that I don't want to, and the other file (4) I want to stash it all.

How can I stash in this scenario?

Update: in case of stash specific files its possible with git stash push -m _STASH_MESSAGE_ _PATH_1 _PATH_2 In my case, I need to stash part of file change (for example lines 1-20 has been changed, but I want to stash only 1-12 lines and keep 13-20 lines to work on)

Netanel.R
  • 153
  • 1
  • 7
  • 2
    Possible duplicate of [How can I git stash a specific file?](https://stackoverflow.com/questions/5506339/how-can-i-git-stash-a-specific-file) – Liam Jul 30 '19 at 10:36
  • Actually, it says how to stash specific files, but in case I want to stash part of file changes it doesn't seem to be answered there... – Netanel.R Jul 30 '19 at 11:12
  • 1
    It does — `git stash --patch`. – phd Jul 30 '19 at 12:52
  • It shows a block of code and asks if I want to use it or not, but I can't choose manually, there are lines in the block which I don't want to use and some of them I want to. – Netanel.R Aug 04 '19 at 07:42

2 Answers2

6

In Git, many of their commands come with a flag -p, or --patch. This flag allows you to interact with certain parts of a file rather than the entire thing.

git stash is no different. From the documentation on git stash;

With --patch, you can interactively select hunks from the diff between HEAD and the working tree to be stashed. The stash entry is constructed such that its index state is the same as the index state of your repository, and its worktree contains only the changes you selected interactively. The selected changes are then rolled back from your worktree.

So in your case, running

git stash -p

Then interactively selecting the parts of the file you want would be enough.

For more information on the commands while in Interactive Mode, see the section titled Interactive Mode in the git-add documentation.

romellem
  • 5,792
  • 1
  • 32
  • 64
0
git stash -p

is a way to review changes chunk by chunk, to let you decide which are to be stashed, and which aren't (as you'd do with git add -p) (doc).

Romain Valeri
  • 19,645
  • 3
  • 36
  • 61