How can you use git diff to display the changes between the latest commit and the one before it?

The git diff command is used to display differences between git trees. To show the changes between the latest commit and the one before it, you can use it in the following manner:

git diff HEAD^ HEAD

Here’s an explanation of the command:

  • git diff is the base command that shows changes between commits, commit and working tree, etc.
  • HEAD refers to the latest commit in your current branch.
  • ^ symbol after HEAD is used to refer to the commit before the latest one. Therefore, HEAD^ indicates the commit before the latest commit.

So, git diff HEAD^ HEAD will display the changes between the latest commit (HEAD) and the commit before it (HEAD^).

The output will show you the changes between these two commits in the format: - (minus) for the old version and + (plus) for the new version. These are shown next to each line of code. The lines of code that didn’t change are also shown for context, without any - or + sign before them.

You might see something like this:

diff --git a/file1 b/file1
index 8aq3d2s..6tr7y6u 100644
--- a/file1
+++ b/file1
@@ -1,2 +1,2 @@
-This is the original line of code
+This is the new line of code
 This line of code has not changed

In this example, the line “This is the original line of code” in file1 was replaced by “This is the new line of code”. The second line, “This line of code has not changed”, remains the same between the two commits.

If you want to see these changes in your default git diff tool (like meld, diffmerge, etc.) you can use the same command with the difftool option:

git difftool HEAD^ HEAD

Remember, understanding how to use these git commands effectively can greatly increase your productivity and efficiency when working on projects with version control.