Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git diff between staged or unstaged changes with a remote branch

Is there a way to do a git diff between staged/unstaged changes with a remote branch say origin/branch1. Is there a similar option with git difftool?

OR

Is there a way to diff changes in my local file system (forget about staged or unstaged) with git remote branch? All I want is to check my changes before committing them. This is really useful once I am done pulling in changes and resolving conflicts with a remote branch.

like image 526
maverick112 Avatar asked Jan 04 '23 03:01

maverick112


2 Answers

Is there a way to do a git diff between staged changes and a remote branch say origin/branch1.

Just run:

git diff --cached origin/branch1

(you may use --staged here if you prefer; I use --cached because git rm has --cached but not --staged). This shows you a way to change origin/branch1 to match what you have staged:

$ git show origin/branch1:README
initial version
$ cat README
initial version
second version
$ echo staged >> README && git add README
$ echo replace whole thing > README
$ cat README
replace whole thing
$ git diff --cached origin/branch1
diff --git a/README b/README
index 42549ca..d9074b8 100644
--- a/README
+++ b/README
@@ -1 +1,3 @@
 initial version
+second version
+staged

If you want to see a way to change what you have staged to match origin/branch1, add -R (reverse the order):

$ git diff -R --cached origin/branch1
diff --git b/README a/README
index d9074b8..42549ca 100644
--- b/README
+++ a/README
@@ -1,3 +1 @@
 initial version
-second version
-staged

As you can see, these are very different from comparing without --cached aka --staged, but this too is easy:

$ git diff origin/branch1
diff --git a/README b/README
index 42549ca..acb8b7a 100644
--- a/README
+++ b/README
@@ -1 +1 @@
-initial version
+replace whole thing

Is there a similar option with git difftool?

These same options (--cached or not, and using any name to identify any commit) are also available with git difftool.


It's worth remembering here that there aren't really any remote branches, in Git. There are commits that you have, and you have names for some of your commits. One possible form of name is a remote-tracking name like origin/branch1. Some people like to call this a "remote branch", but it's just your own (local) Git's memory of where origin's branch1 pointed some time ago, when you ran git fetch origin and had your Git pick up their Git's branches.

like image 161
torek Avatar answered Jan 05 '23 17:01

torek


One way to achieve this is

  • Let's say you have staged changes in one folder dir1
  • Checkout the same repo in another folder dir2, switch to the remote branch
  • Use the unix diff command to see the recursive diff of both the
    directories

diff --brief -r dir1/ dir2/

like image 29
Pankaj Gadge Avatar answered Jan 05 '23 18:01

Pankaj Gadge