git show previous commit that modified a file without git log

328 Views Asked by At

In git we can easily construct revisions pointing to previous commits like HEAD~ HEAD^ and show files on those revisions like

git show HEAD~:myfile

What is the syntax to show the previous version of myfile without first consulting git log to get the commit hash?

I also use fugitive in vim and sometimes needs to open a file's previous version using :Gedit. But I don't know what to supply as argument.

1

There are 1 best solutions below

1
On BEST ANSWER
git show $(git log -m --first-parent --format=%H HEAD~ -2 -- path/to/file | tail -1):path/to/file

Note: This solution requires you to specify the path twice, and can be quite verbose to type every time. An alias would perhaps be better.

git config alias.prev '! f(){ git show $(git log -m --first-parent --format=%H HEAD~ -2 -- "$1" | tail -1):"$1"; }; f'

To get the previous hash:

git config alias.prevhash '! f(){ git rev-parse $(git log -m --first-parent --format=%H HEAD~ -2 -- "$1" | tail -1):"$1"; }; f'