问题
I have 2 strings and I want the git diff between them. I could create file1 and add string1 as its contents.
Then I could create file2 and add string2 as its contents. Then I could git diff file1 and file2.
However, given that I have the strings as strings (and not as file contents) can I avoid these long-winded steps? Is there an easier way?
Something like:
git diff "my first string" "my second string" # obviously does not work
回答1:
If you insist on the git way,
git diff $(echo "my first string" | git hash-object -w --stdin) $(echo "my second string" | git hash-object -w --stdin) --word-diff
回答2:
You don't have to use git diff for that, Git is used to track the changes in your code base.
There is a good linux command for that
diff <(echo "my first string" ) <(echo "my second string")
This is a good answer https://stackoverflow.com/a/454549/4620609
回答3:
In the implementation level, I guess, git diff
use a certain diff utility (such as diff) to generate patch, and redirect to a pager(default it is less
) for viewing. So you need not call git diff
to compare two string.
If you want patch file format as that output by git diff
, the flowing command will be a help.
diff -u <(echo "my first string" ) <(echo "my second string")
-u
is appended to tell diff
to output patch with unified context.
By the way, git provide a configuration item diff.external
to allow you generate diff not by the internal diff machinery, but using the given command. environment variable GIT_EXTERNAL_DIFF
has the same effect.
来源:https://stackoverflow.com/questions/45853613/is-it-possible-to-git-diff-2-strings