TIL: Stage only some changes of a file for atomic commits

Dec. 13, 2023 • TIL, productivity, git

Today, I had to split a larger commit into smaller, atomic commits. I used the following command to interactively stage some of the changes in a file (via this answer on StackOverflow).

git add --patch 

This allows you to decide which changes ("hunks") you want to stage. You can stage with y, not stage with n, and split into smaller hunks with s. Enter ? to print help and all available options, and q once you're done.

If the file you want to add is completely new, first make sure it's tracked with

git add -N 

In more complex cases you can use e to manually edit the hunks you want to stage. To not stage a line, just add a # at the beginning.

In my case, it was useful to be able to edit multiple lines at once. Here is how to do it in vim (via techglimpse.com):

May you be empowered to make each commit atomic!


Recent posts