Magit:查看commit的diff时能否回滚其中单个hunk?
Absolutely! Magit has great granular control over commit changes, so you don’t have to revert an entire commit just to fix one small hunk. Let’s walk through both scenarios step by step:
This is exactly what you need when you want to undo only part of a past commit without touching the rest of its changes. Here’s how:
- Open the Magit Log view: Either run
M-x magit-logdirectly, or from the Magit main buffer (open withM-x magit-status), presslto launch the log. - Locate the commit containing the hunk you want to revert, then press
RETto view its full diff. - Use your arrow keys to navigate to the specific hunk you want to undo (look for the lines starting with
@@ ... @@—those mark the start of each hunk). - Press
v(this triggers themagit-reversecommand). Magit will prompt you to confirm the reversal of this hunk. - Confirm the action, and the hunk’s changes will be undone in your working directory. You can then stage this reversal with
sand commit it like any other change if needed.
This is essentially the same workflow as the first scenario—since viewing a commit’s diff is where you’ll interact with individual hunks. The key difference is you’re already in the diff view when you decide to revert a hunk:
- When you’re in the commit’s diff view (after pressing
RETon a commit in the log), navigate to the target hunk. - Press
vto reverse that hunk. Magit handles the rest, creating the inverse change for just that section of code. - If you want to preview what the reversal will look like before confirming, you can press
C-u vfirst to see a diff of the proposed change.
Pro tip: If you accidentally select the wrong hunk, just press q to exit the confirmation prompt and try again. Magit won’t make any changes until you explicitly confirm.
内容的提问来源于stack exchange,提问作者Gonçalo Marrafa

