A More Sophisticated Example

To get a better understanding of hooks, examine a more sophisticated example.

We'll cover the following

The previous pre-commit scripts were fairly limited in their usefulness. But just to give a flavor of what’s possible, you’re going to give an example that is able to choose whether to allow or reject a commit based on its content.

Banning keywords

Imagine that you’ve decided against o allowing any mention of politics in your code. The following hook will reject any mention of politics (or any word beginning with “politic”).

1	echo 'a political comment' >> file1
2	cat > .git/hooks/pre-commit << EOF
3	> if grep -rni politic *
4	> then
5	> 	echo 'no politics allowed!'
6	> 	exit 1
7	> fi
8	> echo OK
9	> exit 0
10	> EOF
11	git commit -am 'Political comment'

Get hands-on with 1200+ tech skills courses.