Git Diff and Comparing Files/Commits

Git’s diff command is crucial for examining changes made to your project. It highlights differences between files or commits.

git diff:

  • Comparing Working Directory to Staging Area/Last Commit: The simplest use of git diff shows the differences between your current working directory and the last commit (or the staging area if you’ve staged changes). Unstaged changes are shown with a - (deleted) or + (added) prefix. Example:

    git diff
  • Comparing Two Files: You can also compare two specific files:

    git diff file1.txt file2.txt
  • Comparing to a Specific Commit: Compare your current working directory to a specific commit using its hash:

    git diff <commit-hash>

    Use git log --oneline (explained below) to find the commit hashes.

  • Visual Studio Code’s Source Control Editor: VS Code offers a user-friendly interface to view changes, stage them, and commit directly from the source control panel.

Viewing Diff Output:

The output of git diff shows additions with a + and deletions with a -. Moving or renaming files will be presented as deletions and additions. The : character often indicates the end of the diff output for a single file; press ‘Q’ to exit the output.

git log --oneline:

This command displays a concise summary of the commit history, useful when working with many commits:

git log --oneline

It shows each commit hash, branch name (if applicable), and the commit message on a single line. This makes it easy to copy specific commit hashes needed for the git diff command.

Git Lens Extension (VS Code):

The Git Lens extension enhances the diff functionality within VS Code by providing more visual ways to compare changes across branches and commits, making it much easier to navigate a large history.

In Summary:

git diff provides a powerful way to review changes. Coupled with the concise output of git log --oneline and potentially enhanced with the Git Lens extension, you can efficiently navigate and understand the differences between versions of your project.