How can I pass an argument to a shell script being called from a Jenkinsfile?

18 views Asked by At

I have the following code in my Jenkinsfile:

def requirementsPusher(some_argument) {
    sshagent(credentials: ['jenkins-key-new']){
    sh("./build-scripts/pushreqs.sh")
    }
}

I am trying to pass some_argument above into the pushreqs.sh shell script that I am calling.

For reference, my pushreqs.sh looks like this:

#!/bin/bash

set -x  # echo on

. ${0%/*}/common.sh

staged=$(git diff --name-only --staged)
if [ "$staged" == "" ] ; then
    echo "No changes staged, nothing to do"
    exit 0
elif [ "$staged" == "requirements.txt" ] ; then
    echo committing and pushing requirements.txt .. should be only on master and not on rebuild
    git commit --no-verify -m 'Version updates by Jenkins master build' requirements.txt || exit 3
    git push origin HEAD:build_test_latest || exit 2 
    exit 0
else
    echo "Fail - unexpected changes staged: ${staged}"
    exit 5 
fi

I am trying add some_argument- which contains the name of a Jira ticket- to my git commit message.

Just wondering if the above is possible - I looked around for some similar posts around passing argument into shell scripts, but couldn't find any particularly that answers the above.

1

There are 1 answers

0
Benjamin W. On

You have to update the shell script to expect a positional parameter first. In a minimal version:

#!/usr/bin/env bash

ticket=$1

git commit -m "$ticket Version updates by Jenkins master build" requirements.txt

And you have to update the call to pass in the parameter:

sh """
    ./build-scripts/pushreqs.sh "${some_argument}"
"""

The quoting makes sure nothing weird happens if some_argument includes spaces or shell-special characters.