Pritish
Pritish

Reputation: 774

How to capture last part of the git url using shell script?

I am writing a Jenkins pipeline. I am trying to capture last part of the git url without the git extension. For instance: https://github.hhhh.com/aaaaaa-dddd/xxxx-yyyy.git. I want only xxxx-yyyy to be returned. Below is my code:

String getProjectName() {
    echo "inside getProjectName +++++++"
    # projectName = sh(
    #         script: "git config --get remote.origin.url",
    #         returnStdout: true
    # ).trim()
    def projectName= sh returnStdout:true, script: '''
    #!/bin/bash
    GIT_LOG = $(env -i git config --get remote.origin.url)
    echo $GIT_LOG
    basename -s .git "$GIT_LOG"; '''
    echo "projectName: ${projectName}"
    return projectName
}

PS: Please ignore the commented lines of code.

Upvotes: 0

Views: 504

Answers (2)

Cyrus
Cyrus

Reputation: 88776

No space before and after =:

x='https://github.hhhh.com/aaaaaa-dddd/xxxx-yyyy.git'
basename "$x" .git

Output:

xxxx-yyyy

Upvotes: 2

j6t
j6t

Reputation: 13507

There is basic Bourne shell functionality that achieves that:

# strip everything up to the last /
projectName=${GIT_LOG##*/}
# strip trailing .git
projectName=${projectName%.git}

This leaves just the requested name in projectName.

Upvotes: 4

Related Questions