Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
a pre-commit hook for git to remove trailing whitespace
# A git hook script to find and fix trailing whitespace
# in your commits. Bypass it with the --no-verify option
# to git-commit
# Ref -
if git rev-parse --verify HEAD >/dev/null 2>&1
# Initial commit: diff against an empty tree object
# Find files with trailing whitespace
for FILE in `exec git diff-index --check $against -- | sed '/^[+-]/d' | (sed -r 's/:[0-9]+:.*//' > /dev/null 2>&1 || sed -E 's/:[0-9]+:.*//') | uniq` ; do
# Fix them!
(sed -i 's/[[:space:]]*$//' "$FILE" > /dev/null 2>&1 || sed -i '' -E 's/[[:space:]]*$//' "$FILE")
git add "$FILE"
echo "NOTE: removed trailing whitespace from $FILE"

This comment has been minimized.

Copy link

@lez lez commented Apr 23, 2016

(sed -r 's/:[0-9]+:.*//' > /dev/null 2>&1 || sed -E 's/:[0-9]+:.*//')
^ is this for PC / Mac compatibility? It's broken on Linux. The first sed will match, the output will be sent to /dev/null, and there's nothing left to iterate on.

better setting up a $SED environment variable containing 'sed -r' or 'sed -E' upfront if you insist on out-of-the box compatibility.

Great stuff though, thanks a lot for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment