How To Ignore Whitespace With Git Diff?
The git diff command helps developers see the changes between two data sources (commits, branches, etc.). However, sometimes this command shows whitespace differences between two commits. This behavior can be annoying for some developers. Luckily, Git offers many options to fix this problem and ignore whitespaces.
To ignore all line whitespaces with the git diff command, use the ignore-all-space option, like so:
bashgit diff --ignore-all-space
This article will explain the git diff command and its options for ignoring whitespaces.
Let's get to it 😎.
What is the git diff command?
The git diff command shows the changes between two data sources.
Those data sources can be commits, branches, files, etc.
Without arguments, the git diff command shows the differences between the working and staging areas.
Why can the git diff command show whitespaces as differences?
Sometimes whitespaces can seem the same but aren't in reality.
Different systems can represent whitespaces with different characters.
It can be:
- a space
- a tab
- a carriage return
- a new line
- a vertical tab
- a form feed
New lines can also be different based on the operating system or the configuration of your development environment.
So it is good that the git diff command shows those as differences.
However, if you want to ignore whitespace differences, Git offers options to do it as well.
How to ignore whitespace with git diff?
The git diff command offers many options for ignoring whitespaces.
Option | Description |
---|---|
--ignore-cr-at-eol | Ignores the carriage return at the end of the line. |
--ignore-space-at-eol | Ignores the whitespace changes at the end of the line. |
-b --ignore-space-change | Ignores the changes with the number of whitespaces. |
-w --ignore-all-space | Ignores all whitespaces. |
--ignore-blank-lines | Ignores the blank line changes. |
To ignore all whitespaces, use:
bashgit diff -w
To ignore end of the line whitespaces, use:
bashgit diff --ignore-space-at-eol
However, sometimes those solutions will not be enough.
You may need to use the word-diff-regex option to define the definition of a word and ignore all whitespaces.
bashgit diff -w --word-diff-regex='[^[:space:]]'
How to ignore line endings?
To ignore carriage return characters at the end of the line, use the ignore-cr-at-eol
option:
bashgit diff --ignore-cr-at-eol
To ignore whitespace changes at the end of the line, use the ignore-space-at-eol
option:
bashgit diff --ignore-space-at-eol
Final thoughts
As you can see, Git offers many options to ignore whitespaces when using the git diff command.
Sometimes, however, you need to combine some or all the options to ignore all whitespaces.
Here are some other Git tutorials for you to enjoy: