Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify "git add" After "git diff"

Tags:

git

Before adding any file to git, I always call git diff <filename> often with additional options (e.g., "-w", "--word-diff", etc.).

Once the diff looks good, I stage the file for the commit via "git add <filename>". The way I currently do this is by modifying the previous command line git diff bash call which entails deleting both the diff and any options which feels inefficient and a redundant approach.

How can I perform the diff and optionally the add together via the command line?

like image 608
ZaydH Avatar asked Sep 17 '25 16:09

ZaydH


1 Answers

To selectively apply diff hunks, use the -p aka --patch option. git add -p applies from worktree to index, git checkout -p applies from index or a named commit to index and worktree, git reset -p applies from a commit to the index.

Your options for each hunk are

Apply this hunk to index [y,n,q,a,d,/,j,J,g,e,?]? 
y - apply this hunk to index
n - do not apply this hunk to index
q - quit; do not apply this hunk or any of the remaining ones
a - apply this hunk and all later hunks in the file
d - do not apply 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 hunks
e - manually edit the current hunk
? - print help

which you get with ? or just hitting enter.

For just generally not repeating yourself at the command line, $_ expands to the previous command's last argument, so e.g. git diff --word-diff @ path/to/file and then just git add $_. There's also history expansion which pulls words from history lines not commands and varies slightly by shell, !$ is "the last word on the previous line", !#$ is "the last word on the line I'm typing now" so in-place sort is e.g. sort -nrk2,2 -o mylist !#$.

like image 91
jthill Avatar answered Sep 20 '25 12:09

jthill