Jenkins substring environment variable

10,764

In bash (I assume that's what you want to know since you tagged the question with it), you can do it by using this syntax: ${string:start_position:length}

You could extract e.g. the first 8 characters of the hash by writing:

${GIT_COMMIT:0:8}

I've taken this solution from here: http://tldp.org/LDP/abs/html/string-manipulation.htm

Share:
10,764
Ben
Author by

Ben

javascript 1167th user (yes!) php 1312th user (wow!) html 476th user (he's good!) css 360th user (quick, hire this guy!) Proud owner of the Tumbleweed badge (his weaknesses are actually strengths!)

Updated on June 04, 2022

Comments

  • Ben
    Ben almost 2 years

    I'm using Jenkins and the Git plugin which offers the following environment variables:

    • GIT_COMMIT: SHA of the current
    • GIT_BRANCH: Name of the branch currently being used, e.g. "master" or "origin/foo"
    • GIT_PREVIOUS_COMMIT: SHA of the previous built commit from the same branch (the current SHA on first build in branch)
    • GIT_URL: Repository remote URL
    • GIT_URL_N: Repository remote URLs when there are more than 1 remotes, e.g. GIT_URL_1, GIT_URL_2
    • GIT_AUTHOR_EMAIL: Committer/Author Email
    • GIT_COMMITTER_EMAIL: Committer/Author Email

    Using the Version Number Plugin, I've got a ${GIT_COMMIT} variable which is read as expected.

    The problem is, it's the full 32 (?) character SHA hash. I'd like to take a substring of it. Is there a way to take a substring of an environment variable in Jenkins?

  • Ben
    Ben almost 10 years
    Great thanks but no dice...looked good for a minute but then nothing. Any other ideas? See my comment on the OP for a bit more detail if it helps.
  • Akos Bannerth
    Akos Bannerth almost 10 years
    So, you want to use the plugin to take one environment variable, and set another one, that is a substring of the first? In this case, this entirely depends on the plugin itself (there is no "generic way" to parse environment variables in Jenkins). Where do you want to use the environmental variable generated by the plugin? Maybe you could skip using a plugin, and get the substring of GIT_COMMIT with the above solution directly in the script where it's needed?
  • Ben
    Ben almost 10 years
    OK thanks, I guess there's not a good way to do this - I don't need it for a script, for now just the display name of the project ("2014-06-25-fb8ce" or something).