I'm trying to write my first git hook for prepare-commit-msg
, I've put this together which behaves exactly as I want it on my Fedora box:
#!/usr/bin/bash
COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3
TRELLO_ID='XXX' # our trello project id
branchName=`git rev-parse --abbrev-ref HEAD`
IFS=/ read commitType issueNumber commitDesc <<< $(echo $branchName)
if [[ -z $issueNumber ]]; then
exit 1
fi
firstLine=$(head -n1 $1)
if [ -z "$firstLine" ] ;then #Check that this is not an amend by checking that the first line is empty
sed -i'.bak' -e "1s/^/Issue $issueNumber: \n/" $COMMIT_MSG_FILE
sed -i'.bak' -e "2a\
Issue link: https://trello.com/c/$TRELLO_ID/$issueNumber \n" $COMMIT_MSG_FILE
fi
I've shared this with a team member who's running on a mac and this keeps failing. Extra info about the mac setup is that it is running zsh but I dont know if that is relevant. I'm not familiar with macs so I wasn't able to help other that echoing a lot in this file when running git commit
. For the record I'm also not that experience with bash.
At first I thought it was an issue with sed
compatibility as other questions I found here revolve around it but after further testing it seems this already fails when splitting the branch name (we're using the convention <type>/<ticket-number>/<desc>
). I've also noticed some importance in syntax using single and double quotes around the file.
One last curiosity, on his mac if we run $ which bash
on his terminal we get /bin/bash
, does that mean the shebang is also wrong? how do people keep scripts like this compatible between linux and mac with so many little details? I also considered rewriting this on python which could bring easier compatibility but I really would like to understand what's needed to make this work on both systems.
Thanks!
#!/usr/bin/env bash
across the two platforms, but I'm not sure if that's your issue/bin/sh
. That means no<<<
operators, no[[
tests, and the like, though.sed -i
doesn't work in a consistent way between macOS and Linux. The argument must be part of the-i
on Linux and a separate argument on macOS. Try using Perl or Ruby with their-i
flag instead.mv -- foo foo.bak && sed '...' foo.bak >foo
is a valid portable alternative to the erratic implementation of the-i
option.