Git Diff Tutorial

beginner
6 min

Git Diff Tutorial

Welcome to our comprehensive guide on git diff! This tutorial is designed to help both beginners and intermediate learners understand and effectively use git diff in their projects. Let's dive in!

Understanding git diff

git diff is a command that shows the differences between your working directory and the last commit, or between two specific commit versions. It's a powerful tool for comparing code and tracking changes in your project.

šŸ’” Pro Tip: git diff is often used to preview changes before committing them.

Installing Git

Before we get started, ensure you have Git installed on your machine. If not, you can download it from Git official website.

Basic Usage of git diff

Let's create a simple project and see git diff in action.

  1. Create a new directory and navigate into it:
bash
mkdir my-project cd my-project
  1. Initialize a new Git repository:
bash
git init
  1. Create a file named app.js and add some code:
bash
echo 'console.log("Hello World!");' > app.js
  1. Make changes to the file:
bash
echo 'console.log("Welcome to my project!");' >> app.js
  1. Compare the changes with git diff:
bash
git diff

This command will output the changes made to the file, like so:

diff --git a/app.js b/app.js index 8e2734e..8f6403b 100644 --- a/app.js +++ b/app.js @@ -1 +1,2 @@ console.log("Hello World!"); +console.log("Welcome to my project!");

šŸ“ Note: The output shows the differences between the versions of the file. The lines starting with - indicate deleted lines, while lines starting with + show added lines.

Comparing Commits with git diff

git diff can also compare two specific commit versions. Let's create a new commit and compare it with the initial commit:

  1. Stage and commit the changes:
bash
git add app.js git commit -m "Add welcome message"
  1. Compare the initial commit with the latest commit:
bash
git diff HEAD~1

This command will show the differences between the initial commit and the latest commit.

Practical Examples and Quiz

Now that you have a basic understanding of git diff, let's put it into practice.

Quick Quiz
Question 1 of 1

What does `git diff` command show in a Git project?


In the next lesson, we'll explore more advanced usage of git diff and learn how to use it effectively in your projects. Stay tuned! šŸš€