You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jenkinsfile执行含正则的Shell命令报错,寻求解决方案

解决Jenkinsfile中SSH执行PM2命令的Groovy转义报错问题

问题根源

原命令在Groovy双引号字符串中,两个点触发编译错误:

  • \s 被Groovy当作转义字符解析,但Groovy不识别\s这个转义序列
  • $4 被Groovy当作变量引用尝试解析,导致语法错误

三种可行解决方案

方案1:使用单引号包裹命令(推荐)

Groovy单引号字符串为纯字面量,不会解析转义字符和变量,仅需转义内部的单引号:

sshTransfer(execCommand: 'pm2 ls | grep -vE \'^\\s*id\\s+\' | awk \'{print $4}\'')
  • 内部单引号用 \' 转义
  • \s 改为 \\s,确保Groovy传递给远程shell时保留单个\

方案2:双引号内转义特殊字符

如果必须使用双引号,需对\和$进行双重转义:

sshTransfer(execCommand: "pm2 ls | grep -vE '^\\\\s*id\\\\s+' | awk '{print \\$4}'")
  • \ 转义为 \\\\(Groovy解析一次为\\,shell再解析一次为\)
  • $ 转义为 \\$,避免Groovy将其识别为变量

方案3:使用三重双引号

适合长命令,转义规则与双引号一致:

sshTransfer(execCommand: """pm2 ls | grep -vE '^\\s*id\\s+' | awk '{print \$4}'""")
  • $ 需转义为 \$
  • \ 转义为 \\

修改后的完整Jenkinsfile示例

pipeline {
    agent any

    parameters {
        string(defaultValue: '', description: 'List of PM2 applications', name: 'PM2_Applications')
    }

    stages {
        stage('SSH transfer') {
            steps([$class: 'BapSshPromotionPublisherPlugin']) {
                sshPublisher(
                    continueOnError: false, failOnError: true,
                    publishers: [
                        sshPublisherDesc(
                            configName: "server-config",
                            verbose: true,
                            transfers: [
                                sshTransfer(execCommand: 'pm2 ls | grep -vE \'^\\s*id\\s+\' | awk \'{print $4}\'')
                            ]
                        )
                    ]
                )
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者Ravi Kyada

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 15:33:39