Skip to main content

Using Git restore to discard changes within a file

Posted in Development and Git

I really like git restore, and one of its superpowers is its patch mode, where we can restore parts (or ‘hunks’) of a file, rather than the whole file at once.

Just like git add’s patch mode, we don’t have to use the full --patch flag; we get a handy -p shortcut. The following command would enter patch mode for every file we’ve edited since our last commit:

git restore -p

Alternatively, we can restore parts of a specific file with:

git restore -p path/to/file.html

Once we’re in patch mode, we just need to work our way through the changes by typing a letter from the multitude of options:

Discard this hunk from worktree [y,n,q,a,d,g,/,j,J,k,K,s,e,?]?

In case you’re not sure what any of those mean (a situation I find myself in all the time!), typing ? and hitting enter gives you a nice reference:

y - discard this hunk from worktree
n - do not discard this hunk from worktree
q - quit; do not discard this hunk or any of the remaining ones
a - discard this hunk and all later hunks in the file
d - do not discard this hunk or any of the later hunks in the file
g - select a hunk to go to
/ - search for a hunk matching the given regex
j - leave this hunk undecided, see next undecided hunk
J - leave this hunk undecided, see next hunk
k - leave this hunk undecided, see previous undecided hunk
K - leave this hunk undecided, see previous hunk
s - split the current hunk into smaller hunkse - manually edit the current hunk
e - manually edit the current hunk
? - print help

Pretty overwhelming… The best place to start is with y (‘yes, discard this hunk’) and n (‘no, don’t discard this hunk’), leaving things like splitting hunks for another day, once you’re more familiar with it all.

Note: git checkout also has a patch mode that does exactly the same as git restore’s patch mode, but the key here is that using the git restore command to restore a file to its previously committed state is both more memorable and semantically correct.

Subscribe

If you enjoyed reading this and want a monthly roundup of my articles delivered to your inbox, just enter your email below.

I don’t collect any data on when, where or if people open the emails I send them. Your email will only be used to send you newsletters and will never be passed on. You can unsubscribe at any time.

More posts

Here are a couple more posts for you to enjoy. If that’s not enough, have a look at the full list.

  1. WWDC 2021 roundup

    Just like last year, I’ve written a list of the announcements that stood out at this year’s World Wide Developer Conference (WWDC).

  2. The trouble with back links

    You’d think that adding a back link to a web page would be straightforward. Well, it turn out that it’s not! Let’s have a look at three ways to do it.