Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Git pre-commit hook to add a new line at the end of a file and remove trailing whitespaces
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments. The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
# Usage:
# Remove the .sh file extension when you put the script in your hooks folder!
# Purposes:
# Add an empty line at the end of the file.
# Remove trailing spaces at the end of a line.
# Source:
# Version: 2011-03-08
# Related:
# Files (not deleted) in the index
files=$(git diff-index --name-status --cached HEAD | grep -v ^D | cut -c3-)
if [ "$files" != "" ]
for f in $files
# Only examine known text files
if [[ "$f" =~ [.](conf|css|erb|html|js|json|log|properties|rb|ru|txt|xml|yml|h|m)$ ]]
# Add a linebreak to the file if it doesn't have one
if [ "$(tail -c1 $f)" != '\n' ]
echo >> $f
git add $f
# Remove trailing whitespace if it exists
if grep -q "[[:blank:]]$" $f
sed -i "" -e $'s/[ \t]*$//g' $f
git add $f

I personally added md, sh and scss as known text files. Good stuff otherwise!

blelump commented May 1, 2015

I came across strange issue on Ubuntu cause it still complained Syntax error: "(" unexpected (expecting "then") whereas the syntax seems to be just fine.

For those who are not familiar with (yet), Ubuntu has dash as default shell and dash does not support regexp comparison so either change /bin/sh to /bin/bash or change condition into if echo "$f" | egrep -q "[.](conf|css|erb|html|js|json|log|properties|rb|ru|txt|xml|yml|h|m)$".

0/10 can't use on windows

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