Jenkins Pipeline字符串提取语法问题求助
Let's sort out your problem: you want to pull out access-server-pd from the git URL git@github.com:project/access-server-pd.git, and your standalone Shell logic works perfectly, but you're hitting syntax snags when trying to implement it in a Jenkins Pipeline with triple quotes. Here's how to fix this, plus a more pipeline-native approach to avoid Shell headaches entirely.
Option 1: Fix the Shell Script in the sh Step
The most common issue with triple quotes in Jenkins Pipeline's sh step is Groovy's string interpolation. If you don't escape $, Groovy will try to resolve Shell variables as Groovy variables, leading to errors. Here's the corrected way to run your original Shell logic:
pipeline { agent any stages { stage('Extract Repo Name') { steps { script { def gitUrl = "git@github.com:project/access-server-pd.git" // Use triple double-quotes for multi-line script, escape $ to preserve them for Shell def repoName = sh( script: """ MYVAR="${gitUrl}" NAME=\${MYVAR%.*} # Trim everything after the last . NAME=\${NAME##*/} # Trim everything before the last / echo \$NAME """, returnStdout: true ).trim() // Remove trailing newline from the output echo "Extracted repo name: ${repoName}" } } } } }
If you prefer avoiding escape characters, you can use single triple quotes and concatenate your Groovy variable directly:
def repoName = sh( script: ''' MYVAR="''' + gitUrl + '''" NAME=${MYVAR%.*} NAME=${NAME##*/} echo $NAME ''', returnStdout: true ).trim()
Option 2: Use Groovy's Native String Handling (No Shell Required)
Since Jenkins Pipeline runs on Groovy, you can skip calling Shell entirely and handle the string directly. This is often faster and eliminates Shell-related syntax pitfalls. Here's how:
pipeline { agent any stages { stage('Extract Repo Name') { steps { script { def gitUrl = "git@github.com:project/access-server-pd.git" // Find positions of the last / and last . def lastSlash = gitUrl.lastIndexOf('/') def lastDot = gitUrl.lastIndexOf('.') // Extract the substring between these positions def repoName = gitUrl.substring(lastSlash + 1, lastDot) echo "Extracted repo name: ${repoName}" } } } } }
For a more concise one-liner:
def repoName = gitUrl.split('/')[-1].split('\\.')[0]
Why Your Original Triple Quote Approach Failed
Most likely, you didn't escape the $ characters in your Shell script. When using triple double-quotes (""") in Groovy, any $ is interpreted as a Groovy variable reference. So writing ${MYVAR%.*} would make Groovy look for a Groovy variable named MYVAR (which doesn't exist), causing a syntax error. Adding a backslash (\${MYVAR%.*}) tells Groovy to leave the $ intact for Shell to process.
内容的提问来源于stack exchange,提问作者Lgalan90

