1

The remote repo has been fetched. How to compare two files in the same commit that is in the remote branch without switching the current local branch? In fact, there is no such corresponding local branch whose upstream branch is the aforementioned remote target branch.

Command-line is appreciated to achieve this goal.

John
  • 2,963
  • 11
  • 33

1 Answers1

3
git diff origin/branch:path/to/file1 origin/branch:path/to/file2

# or
git diff <commit sha>:path/to/file1 <commit sha>:path/to/file2

You can actually put anything that points to a revision before the : : branch name, tag name, <sha>, HEAD, master~5, stash ...

You can also choose to compare two different files from two different commits :

git diff origin/deployment:deploy/config.conf origin/migration:.config/cfg.toml

There are other handy shortcuts which you can use to name commits, one I find myself using often is :

  • @{u} : the upstream branch of current branch (e.g: origin/master if I currently am on master)

See git help revisions for an extensive documentation of the many ways to reach a commit.

Another command worth knowing is git difftool :

# open the same diff as above, but in an external diff viewer :
git difftool <commit sha>:path/to/file1 <commit sha>:path/to/file2
git difftool --tool=kdiff3 ...

IMHO, it particularly shines when comparing directories (note: your question did not ask to compare directories, just mentioning it for other occasions) :

# add the '-d' option :
git difftool -d <commit1> <commit2>

# for example: compare HEAD and its upstream branch
git difftool -d HEAD @{u}
LeGEC
  • 46,477
  • 5
  • 57
  • 104
  • Thank you for the rapid reply. It works for me. Is it possible to make it work for a specific commit id? It only works for the HEAD now. – John Jun 30 '22 at 11:56
  • @John: instead of `origin/branch` you can use anything that points to a commit : branch name, tag name, ``, `HEAD`, ... You can actually compare two different files in two different commits with this command (e.g : `git diff HEAD~2:config/.env HEAD~10:deployment/env.txt`) – LeGEC Jun 30 '22 at 12:06
  • In both arguments, the part before the colon `:` is the commit. Replace it with whatever commit ID you have. – j6t Jun 30 '22 at 12:06
  • @LeGEC Sorry for my poor English. I mean the command mentioned in your last reply only shows the differences between two files of the ***most recent commit*** (i.e. `HEAD`). – John Jun 30 '22 at 12:14
  • @John : I understand, and you wanted to view files in a commit *in the history of* `origin/branch` (like `origin/branch~3`) – LeGEC Jun 30 '22 at 12:16
  • I see. Thank you so much. You save me hours. – John Jun 30 '22 at 12:18