Bash Jenkins-在sh脚本中指定变量

Bash Jenkins-在sh脚本中指定变量,bash,shell,jenkins,jenkins-pipeline,sh,Bash,Shell,Jenkins,Jenkins Pipeline,Sh,我想在脚本中创建一个变量名为POD,以分配kubectl输出,然后在运行kubectl port forward pods时传递此变量 但我收到以下错误 org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: WorkflowScript: 151: illegal string body character after dollar sign; solution: either esc

我想在脚本中创建一个变量名为POD,以分配kubectl输出,然后在运行kubectl port forward pods时传递此变量

但我收到以下错误

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 151: illegal string body character after dollar sign;
   solution: either escape a literal dollar sign "\$5" or bracket the value expression "${5}" @ line 151, column 80.
   e-context ${KUBE_CLUSTER_STAGE}

这是我的剧本

 environment {
                POD = ''
            }
            steps {
                script {
                    withCredentials([file(credentialsId: 'mbtkubeconfig', variable: 'config')]){
                        try {
                            // Expose PostreSQL
                            sh '''#!/bin/sh
                                chmod ug+w ${config}
                                export KUBECONFIG=\${config}
                                kubectl config use-context ${KUBE_CLUSTER_STAGE}
                                kubectl config set-context --current --namespace=database
                                POD = `$(kubectl get po -n database --selector='role==master' -o jsonpath="{.items[0].metadata.name}")`
                                kubectl port-forward pods/$POD 5432:64000 & echo \$! > filename.txt
                            '''
当我在没有变量的情况下尝试时,没有出现任何错误。下面是运行时没有任何错误的脚本

                        sh """#!/bin/sh
                            chmod ug+w ${config}
                            export KUBECONFIG=\${config}
                            kubectl config use-context ${KUBE_CLUSTER_STAGE}
                            kubectl config set-context --current --namespace=database
                            kubectl get pods -n database
                            kubectl port-forward pods/my-postgres-postgresql-helm-0 5432:64000 & echo \$! > filename.txt
                        """

使用
sh
运行命令时,请确保使用的是
而不是
。只有在使用
“${config}”
时才会解析Groovy变量

顺便说一句,使用
env.
标记变量被认为是最佳实践,尽管不需要解析变量。例如,尝试使用
${env.KUBE\u cluster\u stage}标记集群阶段