7

I wrote a script

#!/bin/bash
commit_msg=$1
echo "Your commit message: $commit_msg"

in hooks/commit-msg which validates the commit message in

git commit -m "fixed a bug"

But when I run the hook, I have:

Your commit message: .git/COMMIT_EDITMSG

instead of

Your commit message: fixed a bug

How can I capture the commit message into a variable?

I've read How to capture a git commit message and run an action but it didn't help me because that hook was for post-receive and I need it for commit-msg so I don't have my commit message in

git log -1 HEAD --pretty=format:%s

because my hook blocks from doing a commit.

1
  • The parameter passed into the commit-msg hook is the path to the commit message file. If you were to open the file at that path you will find the commit message.
    – Maggie S.
    Commented Oct 24, 2018 at 17:39

1 Answer 1

11

From the docs:

The commit-msg hook takes one parameter, which again is the path to a temporary file that contains the commit message written by the developer

Therefore, you need to read the contents of the given file to provide the message:

commit_msg=$(cat "${1:?Missing commit message file}")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.