Wrangle Wandering Whitespace with Git (?!?)

FacebooktwitterlinkedinmailFacebooktwitterlinkedinmailby feather

While I was watching a course on Pluralsight, Advanced Git Tips and Tricks, I came across a feature that I had never heard of before, but well worth knowing. Did you know you can wrangle wandering whitespace with Git?

You may have already noticed that Git shows you trailing whitespace when you use the git diff command.

Git diff showing extra whitespace
Git diff showing extra whitespace

As you can see, Git has highlighted the unnecessary space at the end of some of the added and changed lines.

Configuring how Git handles whitespace

You can control which whitespace Git will highlight with your .gitconfig file.  For instance, to have Git highlight tabs when you use them for indenting, instead of spaces, you can configure Git with this command.

git config --global core.whitespace "tab-in-indent"

Some helpful options are:

  • "blank-at-eol" – show space at end of lines
  • "blank-at-eof" – show space at end of files
  • "tab-in-indent" – show tabs in indentation
  • "indent-with-non-tab" – show spaces in indentation (opposite of the previous option)

For a complete list of whitespace configuration options, check out the core.whitespace section of the manpage for the git-config command.

Making Git stop on whitespace errors

Ever how you set up whitespace handling in Git, you can make Git show you what you consider whitespace errors. You do this by adding the --check option to the diff command.

git diff --check
git diff --check showing whitespace errors
git diff –check showing whitespace errors

When there are whitespace errors, this command returns an error code. That means, if you put this line in a pre-commit hook, then git will not let you commit code that has whitespace you do not want.

Automatically correcting whitespace errors

If you didn’t check for whitespace errors before you committed, but want to fix any whitespace errors in the last commit, you can use the git rebase command with an option.

Check your previous commit.

git diff HEAD~1 HEAD

If you see whitespace errors, and you haven’t yet pushed those changes to a remote repo, ask Git to fix them for you.

git rebase HEAD~1 --whitespace=fix


This short article has shown a neat and very helpful feature of Git. It will show you errors in your code’s whitespace, according to how you’ve configured Git. It will even help you prevent unwanted whitespace from sneaking into your commit, or help you remove that whitespace if it does.

3 thoughts on “Wrangle Wandering Whitespace with Git (?!?)”

Leave a Reply

Your email address will not be published. Required fields are marked *