jenkinsgroovyjenkins-pipelinejenkins-groovy

How do you run ssh /bin/bash << EOF commands in groovy?


I entered the following code into my bash shell:

export letters="a b c"
ssh centos@x.x.x.x /bin/bash << EOF
echo $letters
for letter in ${letters}; do
    echo "hello \$letter"
done
EOF

And got the expected output

a b c
hello a
hello b
hello c

However, when I wrote a groovy script to do the same:

pipeline {
    stages {
        stage('print letters') {
            steps {
                script {
                env.letters="a b c"
                sh'''
                    ssh centos@x.x.x.x /bin/bash << EOF
                    echo $letters
                    for letter in ${letters}; do
                        echo "hello \$letter"
                    done
EOF
'''
                }
            }
        }
    }
}

I get

a b c
hello 
hello 
hello 

So all of the variables being set in the ssh shell are being ignored.


Solution

  • Groovy string syntax swallowed one level of \ escaping. You would need to escape \ to pass it to shell.

                            echo "hello \\$letter"