首页 > 解决方案 > 从詹金斯执行shell脚本时如何将变量作为参数传递

问题描述

我在 Jenkins 中有一个管道脚本并执行如下所示的 shell 脚本。

steps {
                script {
                    def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
                    com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
                    Jenkins.instance,
                    null,
                    null
                    );
                    for (c in creds) {
                        if(c.id == '9d64a593-d40d-4ba2-9ec8-6bxxxxxxxxx') {
                            println( ( c.properties.password ? "ID: " + c.id + ", UserName: " + c.username + ", Password: " + c.password : ""))
                            uname = c.username
                            pwd = c.password
                            println("uname - " + uname)
                            sh './runUIContainerLogin.sh "${uname}" "${pwd}" '
                        }
                         
                    }
                }
            }

最后,当我运行 shell 脚本 runUIContainerLogin.sh 时,尽管我在脚本中分别提到了 'uname' 和 'pwd' 的 $1 和 $2,但变量并没有传递给脚本。我在 shell 脚本中得到 uname 和 pwd 的空值(“”)。

请帮助我获取在 runUIContainerLogin.sh 执行时传递的脚本中的变量值。

标签: linuxshellunixjenkinsjenkins-pipeline

解决方案


I would try these steps to help resolve your problem.

  1. Test what is passed into the sh commandline
  2. If correct call sh with double quotes and remove the single quotes
  3. Call the sh commandline with " and reomve the single quotes from varaiables.

sh "./runUIContainerLogin.sh ${uname} ${pwd}"

Example:

def uname= 'Jenkins'
echo "${uname}"

Results in:

Jenkins

Here is some documentation including use cases handling credentials based on setting the username and password.


推荐阅读