Last active
August 29, 2015 14:15
-
-
Save koninka/4a5e0a933799948c951f to your computer and use it in GitHub Desktop.
Git pre-commit hook to add a new line at the end of a file and remove trailing whitespaces
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
files=$(git diff-index --name-status --cached HEAD | grep -v ^D | cut -c3-) | |
if [ "$files" != "" ] | |
then | |
for f in $files | |
do | |
# Only examine known text files | |
if [[ "$f" =~ [.](conf|css|less|erb|html|js|json|log|properties|rb|ru|txt|xml|yml|php|twig)$ ]] | |
then | |
# Add a linebreak to the file if it doesn't have one | |
if [ "$(tail -c1 $f)" != '' ] | |
then | |
echo >> $f | |
git add $f | |
fi | |
# Remove trailing whitespace if it exists | |
if grep -q "[[:blank:]]$" $f | |
then | |
sed -i "" -e $'s/[ \t]*$//g' $f | |
git add $f | |
fi | |
fi | |
done | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment