git - trim whitespace

Zaz picture Zaz · Jul 30, 2010 · Viewed 13.9k times · Source

I've accidentally put some whitespace in my initial commit - it shows up red in git diff --color. What's the best way to get rid of the existing whitespace and how can I avoid this happening again?

I am not necessarily looking for a built-in git command. Any external program available for free on Ubuntu would also be welcome.

Answer

Zaz picture Zaz · Jul 30, 2010

To trim trailing whitespace on all files in the current directory, use:

sed -i 's/[[:space:]]*$//' *

To warn about future whitespace errors (both trailing spaces and spaces before tabs), and to fix whitespace errors in patches, add the following code to your gitconfig file:

[core]
    whitespace = trailing-space,space-before-tab
[apply]
    whitespace = fix