1

Is there a way to add line by line in git.

I tried this:

git add -p 

But this command is not performant for me. because I need to treat each line separately.

If there is no a solution, I'm surprised about how git community forgot to add this feature.

  • Have you tried splitting the chunks? – Paolo Apr 28 '20 at 13:29
  • "*I'm surprised about how git community forgot to add this feature.*" Easy to understand — nobody needs the feature. Adding a hunk — yes, we need it. Added just one line from a hunk? Why? – phd Apr 28 '20 at 15:48

1 Answers1

5

You can add a lines separately with git add -p, but it can be a bit involved.

(1/1) Stage this hunk [y,n,q,a,d,e,?]? 

When you get this prompt, you can first try splitting the hunk into smaller hunks with s key. This will split non-continuous changes. If this does not get what you want, you can press e to manually edit the hunk. After you press e an editor window will open with the hunk.

Here you have to 'disable' all the lines you do not want to add (by default all lines will be added):

  • To disable + (plus) lines, delete the line completely (do not leave empty line)
  • To disable - (minus) lines, replace the minus at the beginning with ' '(single space).
  • To cancel the edit, delete all lines, save and quit.

These instructions will be present in the editor as comments.

After editing, you can save and quit. Only the 'enabled' lines will be added to index. You can repeat this for any hunks you want to edit.

This feature is available for git reset -p and git checkout/restore -p and other interactive patch commands, but the instructions for them may be different.


There is also a git add -e command where you will be given a similar patch of all the unstaged changes. You can do the same thing there but it can be even more confusing, especially for large changes.

Emil M George
  • 356
  • 2
  • 8