Skip to content

Instantly share code, notes, and snippets.

Last active Sep 19, 2020
What would you like to do?
Github pre-commit hook to prevent commits of large files
# This is a pre-commit hook that ensures attempts to commit files that
# are larger than 100 MB to your _local_ repo fail, with a helpful error
# message.
# This prevents the local repo from getting out of sync with the Github
# repo. To install
# 1) Change this file to executable:
# $ chmod a+x pre-commit
# 2) Move into the .git/hooks directory at the top-level of the repo
# $ mv pre-commit .git/hooks/
# See blog post on
function file_too_large(){
# This command is more portable, but harder to reason about
# filesize=`echo $1 | awk '{ mb =$1 / 1024 / 1024; print mb " MB"}'`
filesize=$(( $1 / 10**6 ))
File $filename is $filesize MB, which is larger than github's maximum
file size (100 MB). We will not be able to push this file to Github.
Commit aborted
empty_tree=$( git hash-object -t tree /dev/null )
if git rev-parse --verify HEAD > /dev/null 2>&1
for file in $( git diff-index --cached --name-only $against ); do
file_size=$( ls -la $file | awk '{ print $5 }')
if [ "$file_size" -gt "$limit" ]; then
file_too_large $filename $file_size
exit 1;
Copy link

benmccallum commented Nov 28, 2019

I had issues with modified files that had spaces in their name and also my cwd was different so I have it cd to the repo root straight away so the staged file paths make sense. Posted here. Got it working with Husky. Thanks for the share!

Copy link

kiwidamien commented Dec 2, 2019

Copy link

benmccallum commented Dec 2, 2019

No worries!

Copy link

benmccallum commented Jan 6, 2020

FYI, another fix picked up by @guysmoilov over here that's prob worth a blog update too.

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