How to Interactively discard selected changes in git

GIT is offering us the way to discard selected changes interactively. Here is how you will do it,

To checkout or discard selected changes from all modified files

git checkout -p  

If you want to checkout or discard selected changes from specific file, give that file as an argument

git checkout -p  file_name

As per this command git will break down the file into chunks called hunks. After you execute this command, you will be prompted with following question with several options to choose.

Discard this hunk from worktree [y,n,q,a,d,/,e,?]?

Here is the description of each option,

y – discard this hunk from worktree
n – do not discard this hunk from worktree
q – quit; do not discard this hunk nor any of the remaining ones
a – discard this hunk and all later hunks in the file
d – do not discard this hunk nor 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 hunks
e – manually edit the current hunk
? – print help

You can also unstage the selected changes from all staged files or from specific file.

To unstage selected changes from all staged files use following command

git reset HEAD -p

To unstage changes from specific file give that file as an argument.

git reset HEAD -p  file_name

Here also you will be prompted to choose any one of the option to unstage hunk.

 

Leave a Reply

Your email address will not be published. Required fields are marked *