Jenkins 管道中的多行 bash 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44842259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:15:41  来源:igfitidea点击:

Multiline bash command in Jenkins pipeline

linuxbashjenkins

提问by tig

I have the following sh command in my Jenkinsfile which does not work because it tries to execute the last "DATA" as a command. If I move last "DATA" to the beginning of the line it works but is not as beautiful as I want. Is there a way to the indention in this case?

我的 Jenkinsfile 中有以下 sh 命令,它不起作用,因为它试图将最后一个“数据”作为命令执行。如果我将最后一个“DATA”移到行首,它可以工作,但没有我想要的那么漂亮。在这种情况下有缩进的方法吗?

    sh """
        sshpass -p 'password' ssh -o StrictHostKeyChecking=no appsadm@$backup_registry <<DATA
        sudo /etc/init.d/docker stop || true
        sudo yum remove -y docker-engine.x86_64
        sudo rm -fr /var/lib/docker /var/log/docker
        sudo rpm -iUvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm || true
        sudo yum update -y
        sudo yum -y install docker-io
        sudo sed -i 's#other_args=.*#other_args="--insecure-registry $official_registry:5000"#g' /etc/sysconfig/docker
        sudo /etc/init.d/docker start
        DATA
        """

采纳答案by Nahuel Fouilleul

because <<DATAspecifies the end of here-doc <<-DATAsuppress leading tabs but not spaces

因为<<DATA指定 here-doc 的结尾<<-DATA抑制前导制表符而不是空格

cat <<-DATA
    hello
<tab>DATA

another option is to add spaces in marker

另一种选择是在标记中添加空格

cat << "    DATA"
    hello
    DATA

回答by waaffles

I know this is an old question, but I had ran into this at some point, and eventually ended up using stripIndent()

我知道这是一个老问题,但我在某个时候遇到过这个问题,最终使用了 stripIndent()

steps {
    echo 'Deploying....'
    sh """
    ssh somewhere <<EOF
    cd somewhere
    do some more stuff
    EOF
    """.stripIndent()
}

That way you can still keep your indentations and formatting

这样您仍然可以保留缩进和格式

回答by Jadda

Edit:We don't need to use EOF, simply put the semicolon at the end of statement on multiline shell script as shown below

编辑:我们不需要使用 EOF,只需将分号放在多行 shell 脚本的语句末尾,如下所示

sh """ if [ -d /opt/tomcat/apache-tomcat-8.5.38/webapps/ROOT ] ;
       then ;
            ssh $USERNAME@$DEV_HOSTNAME 'sudo rm -rf /opt/tomcat/apache-tomcat-8.5.38/webapps/ROOT' ;
            echo 'ROOT directory deleted successfully' ;
       fi ;
"""