bashshelljenkinsjenkins-pipeline

Echo content of a string variable containing a dollar


I have seen How to echo a variable containing an unescaped dollar sign in Bash. However, my case is slightly different.

I have my variable, var. I want to echo the content of the variable var. A command such as

echo ${var}

or

echo "${var}"

is globally fine.

However, in one case, this variable took the value

var=abdc$32

And in this specific case, my 'echo' does not work as it does not print abcd$32 as expected as it interprets the $ sign.

I am not the one assigning the value for the variable, and that is why an assignment

var='abcd$32'

cannot be done.

The variable is actually a password I extract from the Jenkins Credential Binding plugin. See https://www.jenkins.io/doc/pipeline/steps/credentials-binding/.

Syntax:

withCredentials([usernamePassword(credentialsId: 'my_credential', passwordVariable: 'MY_PASSWORD', usernameVariable: 'MY_USERNAME')])
{
                   sh "echo MY_PASSWORD ${MY_PASSWORD} "
}

If I put a single quote,

 sh 'echo MY_PASSWORD ${MY_PASSWORD} '

the password would be hidden (which is what you would actually expect from the plugin).

How could I do so that I can 'echo' the real content of the variable MY_PASSWORD?


Solution

  • As said in comments by @markp-fuso, the dollar sign is being interpreted during the assignment: var=abcd$32

    This is the shell quoting basics, so, instead:

     var='abdc$32'
     echo "$var"
    

    Learn how to quote properly in shell; it's very important:

    "Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'. See
    http://mywiki.wooledge.org/Quotes
    http://mywiki.wooledge.org/Arguments
    http://wiki.bash-hackers.org/syntax/words