Search code examples
bashgitgithookspre-commit-hookcommit-message

Commit message file missing in commit-msg hook


I'm trying to write a commit-msg hook to format my commit messages to wrap at a maximum column width:

#!/bin/bash

format_max_column_width() {
  MAX_LINE_LENGTH_CHARS=50

  cat "$1" | grep -v "^Bug: |^Change-Id: |^Signed-off-by: |^CC: " > body
  cat "$1" | grep "^Bug: |^Change-Id: |^Signed-off-by: |^CC: " > footer
  fmt -w "$MAX_LINE_LENGTH_CHARS" body > body
  cat body > "$1"
  cat footer >> "$1"
  rm body footer
}

format_max_column_width

For some reason, when I make a commit, I get the following errors because $1 seems to be empty.

cat: '': No such file or directory
cat: '': No such file or directory
.git/hooks/commit-msg: line 9: : No such file or directory
.git/hooks/commit-msg: line 10: : No such file or directory

Moreover, if I just echo $1, nothing will be printed, confirming this theory. What's going on?


Solution

  • Inside a shell function $1 means "the first parameter to the function", not to the script. You need to pass the first script parameter further to the function:

    format_max_column_width "$1"