Not able to access value of a jenkins groovy variable in shell script for loop

Jenkinsshell-scripting

When i am passing value of a variable declared in jenkins Groovy script its value is not retained in "for" loop which runs on a remote server. Strange thing is i am able to access the same value on remote server outside the for loop.

Here is the sample code i am trying to use

#!/usr/bin/env groovy

def config
def COMMANDS_TO_CHECK='curl grep hello awk tr mkdir bc'
pipeline {

    agent {
        label "master"
    }

    stages {
            stage ('Validation of commands') {         
            steps {
                script {
                    sh """
                    #!/bin/bash
                    /usr/bin/sshpass -p passwrd ssh user@host << EOF
                    hostname

                      echo $COMMANDS_TO_CHECK ---> This is printed
                          for CURRENT_COMMAND in \$COMMANDS_TO_CHECK
                        do
                        echo ${CURRENT_COMMAND}  ---> Why This is not printed?
                        echo \${CURRENT_COMMAND} ----> Why This is not printed?
                        done
                        hostname
EOF
                        exit

"""

}
}
}
}
}

OutPut

[workspace@3] Running shell script
+ /usr/bin/sshpass -p passwrd ssh user@host
Pseudo-terminal will not be allocated because stdin is not a terminal.
illinsduck01
curl grep hello awk tr mkdir bc
illinsduck01
+ exit

Best Answer

Remove the backslash in front of $COMMANDS_TO_CHECK, so:

for CURRENT_COMMAND in $COMMANDS_TO_CHECK

This is because COMMANDS_TO_CHECK is a Groovy variable and will be interpreted by Groovy inside of double-quoted strings.

Also use a backslash in front of $CURRENT_COMMAND, so:

echo \${CURRENT_COMMAND}

This is because CURRENT_COMMAND is a shell variable, not a Groovy variable, so you do not want it to be interpreted by Groovy inside of double-quoted strings.