How to use git diff while excluding files

Greg Foster
Greg Foster
Graphite software engineer

git diff is used to show the differences between two objects in a Git repository. These objects can be commits, branches, the working directory, and the staging area (index). By default, git diff will show you differences that are not yet staged.

  • Focus: Focus on significant changes by excluding files or directories that don't require review (like configuration files, logs, or dependencies).
  • Noise reduction: Reduce clutter in diff outputs, making it easier to spot important changes.

Git does not include a built-in parameter specifically for excluding files directly in the git diff command, but you can achieve this by combining Git attributes or using pathspec filtering.

A .gitattributes file is a configuration file used by Git to define attributes and settings for files in a repository. It allows users to specify custom behaviors such as text or binary handling, line ending normalization, and merge strategies for specific file types. This file is similar to the Git .config file, but specifically defines attributes and settings for files within a repository, while the git config generally deals with broader configuration settings for Git itself.

We can leverage a .gitattributes file to ignore files when executing the git diff command.

  1. Create or modify a .gitattributes file in your repository root.

  2. Add rules to ignore changes for specific files or directories. For example:

    # Ignore changes in specific config files
    secret.config -diff
    # Ignore changes in a specific directory
    logs/ -diff

    In this file, -diff tells Git to treat changes in these files as if they are binary and without any diff to output.

  3. Test your configuration:

    git diff

    After setting up the .gitattributes file, changes to the specified files or directories should no longer appear in the diff.

Git supports pathspec patterns in many commands to limit the scope of certain Git operations. To exclude certain files or directories from your git diff output, use the :(exclude) pathspec.

  1. Basic usage:

    git diff -- . ':(exclude)path/to/exclude'

    This command shows changes for all files in the current directory, except those in path/to/exclude.

  2. Exclude multiple paths:

    git diff -- . ':(exclude)path/to/exclude' ':(exclude)another/path/to/exclude'

    Use multiple :(exclude) patterns to exclude many files or directories.

For further reading, see the official Git documentation.

Stay unblocked. Ship faster.
Experience the new developer workflow - create, review, and merge code continuously. Get started with one command.
Get started

Give your PR workflow
an upgrade today

Stack easier | Ship smaller | Review quicker

Or install our CLI.
Product Screenshot 1
Product Screenshot 2