Netanel.R
Netanel.R

Reputation: 153

How to use git stash in order to stash partial changes?

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)

Upvotes: 2

Views: 1398

Answers (2)

Romain Valeri
Romain Valeri

Reputation: 22065

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).

Upvotes: 0

romellem
romellem

Reputation: 6503

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.

Upvotes: 6

Related Questions