How to parse the commit hash from the result of gi

2019-03-05 15:36发布

Something I often do is to call git blame for a single line of code, and then git show the resulting commit hash and paste it onto the clipboard to show on https://diffy.org/:

$ git blame some/file.py -L 324,324
660b7c56 some/file.py (John Doe 2017-02-14 15:39:30 -0500 324)         print("Hello, world!")
$ git show 660b7c56 | pbcopy

I would like to automate this process somewhat and create a bash function which takes as input a file path and line number (some/file.py and 324, respectively, in this example) and has as a side effect that the git show result for that commit hash is pasted to my clipboard.

What would be the best way to go about this? So far I've tried

$ git blame some/file.py -L 324,324 | cut -f 1 -d " " | git show

but this doesn't seem to show the differences in the commit I'm interested in, but just a summary. I think I'm not really using pipes properly because echo 660b7c56 | git show doesn't produce the same result as git show 660b7c56.

(It also seems like git rev-parse is a relevant function but I haven't been able to figure out yet how to apply it).

标签: bash git parsing
1条回答
趁早两清
2楼-- · 2019-03-05 15:59

git show doesn't read arguments on stdin. When you run:

echo 12345 | git show

You are (a) running git show with no arguments and (b) discarding the output of the echo command.

If you want to use the result of your git blame ... command as the argument to git show, you have a couple of options. You can use process substitution, like this:

git show $(git blame some/file.py -L324,324 | cut -f1 -d" ")

In this case, the shell replaces the $(...) expression with the output produced by that pipeline.

You could also use xargs:

git blame some/file.py -L324,324 | cut -f1 -d" " | xargs git show

The xargs command reads lines from stdin and then passes them as arguments to the given command.

查看更多
登录 后发表回答