git hooks bash -- getting the commit message

With following command:

cat $1

will print your commit message in commit-msg


The answer depends slightly on what you're trying to do with the commit message. There are three hooks you could be asking about:

  • prepare-commit-msg is run immediately after the default message is prepared, before the user edits it. The first argument is the name of the file with the commit message. (The second argument indicates where the message came from.)

  • commit-msg is run after the commit message is edited/finalized, but before the commit takes place. If you want to fail the commit if the user's commit message is bad, or to modify the message, you want this, and the single argument is the name of the file with the commit message.

  • post-commit is run after the commit. It has no arguments, but you can of course get the message from git log -n 1 HEAD (probably with --format=format:%s%n%b or some such). If all you want to do is look for something in the message, and notify based on it, you should use this.

All of this material is taken from the githooks manpage

As for running it only on the main branch, all you need is something like:

if [ "$(git symbolic-ref HEAD)" == "refs/head/master" ]; then
    # do your stuff
fi

Tags:

Git

Bash