brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: stage only part of a file with git add -p

Git
~/tips/tip-git-add-patch

git add -p

Lets you choose which parts of a file go into the next commit.

One file, two unrelated changes. That should be two commits, and git can do that for you.

git add -p

The -p stands for patch. Git walks through your changes hunk by hunk and asks what to do with each one. The answers I use most:

y  stage this hunk
n  do not stage this hunk
s  split the hunk into smaller hunks
e  edit the hunk by hand
q  quit

The s answer is the useful one. If two changes sit close together, git shows them as one hunk. Press s and git cuts it up where there are unchanged lines between them. If it cannot split any further, e lets you edit the patch yourself.

Once you are done, only the hunks you said yes to are in the index. Commit them, then run git add -p again for the rest. Your history reads as separate changes instead of one lump called "fixes".

A good habit is to run git diff --staged afterwards to see what you really staged.

The caveat: this compares the index with your working tree, so it works on files git already knows. A new file has to be added the normal way first. And if you want to skip pressing return after each answer, the docs mention the interactive.singleKey setting.

Further reading: git add documentation, On this site: unstage a file with git restore –staged, On this site: git diff –staged shows what your commit will contain

More Git tips git show-branch main feature git log --stat -5 git merge --no-ff feature -m "Merge feature" git merge --squash feature git merge --abort All Git tips (144) All topics

Link