Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

How do you selectively stage several hunks from command line in git? - Imagine you edited a large file, fixed two different things, now you‘d like to select the changes related to one thing first and commit them. And then the next changes.

In Magit you visit the file you changed, hit `C-x g' and see all diffs. Now you can review and select hunks by hitting „s“ (stage), go to the next relevant hunk and hit „s“ again to mark for staging. And when you‘re done selecting all changes that are relevant for one ticket, you hit „c“ twice to write a commit message. And off to the modifications/ hunks regarding second ticket.

So how‘d you do this in command line?



This may have been semirecently been added to git, but look into [0]: git add -i It launches a fairly simple interactive text UI that allows you to select files to stage, and it allows one to "patch" into the staging area, which works by showing you a bunch of hunks, asking for each if you want to stage it (or you can even edit a hunk in your $EDITOR).

I'm sure it's not nearly as nice as Magit's UI, but I've been a happy user of this feature for a while.

[0]: https://git-scm.com/book/en/v2/Git-Tools-Interactive-Staging


How about

$ git add -p path/to/the/file

?

Combine this with your favorite tool for command line auto-completion of paths (and, maybe, a git alias to avoid typing `git add -p` all the time) and it's extremely fast.


I am presented with one hunk at a time, and have to decide if I want to stage or not (with a text "menu" underneath it: "(2/2) Stage this hunk [y,n,q,a,d,k,K,g,/,e,?]?"

And then I navigate with j/k (down/up).

Yes, it does the job. Matter of preference.

But if you worked eagerly on three / four different topics and try next to create several different commits by getting a visual overview of all hunks with the abilitiy to selectively stage is a little more comfortable.


If you have multiple files then you can choose to omit the file name and git will let you decide on each hunk for each file.

You can also hit "s" to split a hunk to only commit a part of a hunk of if you want fine grained control you can hit "e" to edit just that hunk in your $EDITOR to only select a specific line or whatever you want.

Personally I tried fugitive and other git clients in the past and always come back to git add -p on the command line. It just feels the most natural and it also forces you to look at the hunks, so there's really no chance you'll accidentally forget to add something.

When using GUIs with sidebars showing what files changed, etc. it's easy to forget to add something because you skim it without really paying attention to what was changed.




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: