I am writing a Makefile and would like to capture the current branch name in a variable to be passed into a --define. Since the script sometimes but not always runs on travis the git repository might be in detached state.
I can extract the branch name on the command line but unfortunately not capture it in a variable. It seems as if the print $$2 does not work within the Makefile environment.
My current line is:
BRANCH := $(shell git for-each-ref --format='%(objectname) %(refname:short)' refs/heads | awk "/^$$(git rev-parse HEAD)/ {print $$2}")
and I get
dfd943a57015dbd2129ca7b7033c4e1749f18974 BRANCH_NAME
instead of just
BRANCH_NAME
The accepted answer has a problem reliably extracting the branch name (the hash is ok). If the current HEAD commit is the current head of multiple branches then the value of BRANCH will be "branch1 branch2", which will produce unexpected results in your Makefile.
Simply use:
BRANCH := $(shell git rev-parse --abbrev-ref HEAD)
HASH := $(shell git rev-parse HEAD)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With