Search code examples
bashgitgithooks

Git BASH - Hook on merge removes line breaks


I am using a git hook in my prepare-commit-msg to automatically prepend branch names to the commit message:

#!/bin/sh
NAME=$(git branch | grep '*' | sed 's/* //')
echo "$NAME"' - '$(cat "$1") > "$1"

However if I do a git merge, all of the line endings are removed. This causes an issue because git will automatically include lines with comments starting with a # which include things like files that were changed.

So what winds up happening during a merge is something like this:

my_branch_name - Merge branch 'master' into my_branch_name # Conflicts: # File1.txt # File2.txt # File3.txt

Instead of:

my_branch_name - Merge branch 'master' into my_branch_name
# Conflicts:
# File1.txt
# File2.txt
# File3.txt

Solution

  • It's not caused by a merge commit. $(cat "$1") always removes the line endings. If you use git commit without -m "some message", it also raises the issue.

    Try sed, to insert the branch name at the beginning of the first line.

    #!/bin/sh
    NAME=$(git branch | grep '*' | sed 's/* //')
    sed -i '1i'$NAME' - ' $1