The git add -p command allows interactive staging of hunks or parts of a file ( https://git-scm.com/book/en/v2/Git-Tools-Interactive-Staging).
Is there a way to stage a hunk non-interactively? Say, I have these hunks:
$ git diff diff --git a/test.txt b/test.txt index 77e67ac..34eabb1 100644 --- a/test.txt +++ b/test.txt @@ -1,4 +1,4 @@ -this is the first change +this is the first change, don't stage it! @@ -6,5 +6,5 @@ this is the first change -this is the first change +this is the second change, stage it! It would be nice to run a single command like git add -p 2 to stage the second hunk without going through the interactive menu.
NOTE: One solution is mentioned here (How to stage chunks non-interactively in git?), but it involves multiple commands and an additional step of editing a patch file.
When would this be useful? Say I was editing a long and repetitive JSON file, and after running git diff, I know I want to stage every other hunk. I don't want to go through each hunk individually; I just want to tell git "stage the 2nd, 4th, 6th, 8th, etc. hunks".
This can also be useful when trying to interact with Sourcetree (which enables working with hunks), using self-defined scripts.
git diff. So, I have "interacted" by runninggit diff, but now I just want to stage a bunch of hunks all at once without going through them one-by-one.