Multiline bash command in Jenkins pipeline

Viewed 19779

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?

    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
        """
3 Answers

I know this is an old question, but I had ran into this at some point, and eventually ended up using 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

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

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 ;
"""
Related