Preventing git commits as root

This is a quick pre-commit git hook to prevent committing annonymously as root – it refuses to allow root to commit directly and insists that –author is given if a user is commmitting via sudo.


#!/bin/bash

abort=0

# Check that if committing as root the author is set, as far as possible.
if [ "$UID" -eq 0 ]
then
echo "Warning: Committing as root." >&2
if [ -n "$SUDO_USER" ]
then
if ! echo $SUDO_COMMAND | grep -q -e '--author'
then
cat - >&2 < or (if you have committed before - see 'man git-commit'):
git commit --author=some_pattern_that_matches_your_name

Previous authors in repository:
$( git log --all --format='%an <%ae>' | sort -u )

EOF
abort=1
fi
else
echo "Committing as root, without using sudo. Please do not do this." >&2
abort=1
fi
fi

if [ "$abort" -ne 0 ]
then
echo -e "\n\ncommit aborted\n" >&2
exit 1
fi

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>