I'm trying to create a function in a Jenkins shared library that spits out the last commit hash of the parent branch of the current git branch.
ParentBranch = foo
ChildBranch(Forked from parent) = bar
What I want to get is the commit hash for the last commit in foo branch
I've written this script and tested it on my local machine
#! /bin/bash
PARENT_BRANCH=$(git show-branch -a | grep '\*' | grep -v `git rev-parse --abbrev-ref HEAD` | head -n1 | sed 's/.*\[\(.*\)\].*/\1/' | sed 's/[\^~].*//')
PARENT_COMMIT=$(git rev-parse $PARENT_BRANCH | cut -c-20)
printf $PARENT_COMMIT
And this works perfectly.
But when I put it in a function in Jenkins, it doesn't seem to do anything. I've tried to escape the special characters too.
def call() {
sh '''
cat <<EOF > gitBranch.sh
#! /bin/bash
PARENT_BRANCH="$(git show-branch | grep '*' | grep -v "$(git rev-parse --abbrev-ref HEAD)" | head -n1 | sed 's/.*\\[\\(.*\\)\\].*/\\1/' | sed 's/[\\^~].*//')"
PARENT_COMMIT="$(git rev-parse ${PARENT_BRANCH} | cut -c-20)"
printf "${PARENT_COMMIT}"
EOF
'''
}
In my Jenkins console output, when I cat the file gitBranch.sh, this is what I get
#! /bin/bash
PARENT_BRANCH=""
PARENT_COMMIT=""
printf ""
Nothing gets expanded.
What am I doing wrong please?