The diff
function in Version control systems enables us to compare changes between two input data sources. The data sources can include files, branches, commits, and so on.
The git diff
command uses the above git data sources as its input and executes the diffing function on them. The git diff HEAD [filename]
command allows you to compare the file version in your working directory with the file version last committed in your remote repository. The HEAD
in the git command refers to the remote repository.
First, we open the gitexample project with a clean working directory. This means that all changes in the repository have been committed. The repository contains a file example.txt
with the string “Hello World!”. Doing a git status
gives us the following output:
On branch main
Your branch is up to date with 'origin/main'.
nothing to commit, working tree clean
Let’s make changes to the example.txt
file. We execute the following echo
command in our working directory to change the contents of the file:
echo "Hello from Educative" > example.txt
Now, let’s execute the git diff HEAD [filename]
command to compare the file version in our working directory and the file version in the local repository:
git diff HEAD example.txt
diff --git a/example.txt b/example.txt
index 980a0d5..ad7204b 100644
--- a/example.txt
+++ b/example.txt
@@ -1 +1 @@
-Hello World!
+Hello from Educative
As we can observe, we can view the exact change that we made. Let’s break down the output in detail:
diff --git a/example.txt b/example.txt
This line displays the two input data sources, a/example.txt
and b/example.txt
, to the git diff
command.
index 980a0d5..ad7204b 100644
This line displays some git metadata that is probably not useful to us.
--- a/example.txt
+++ b/example.txt
This line displays the markers for changes. - - -
represents changes from a/example.txt
and +++
represents changes from b/example.txt
.
@@ -1 +1 @@
-Hello World!
+Hello from Educative
The above lines display the list of diff chunks. Diff chunks refers to the sections of the file with changes. Our output contains only one diff chunk. The first line corresponds to the chunk header, in which -1 +1
indicates that changes have only been made to a single line in the file in our example. The remaining lines display the exact changes made.
Free Resources