Search code examples
mysqlbashescaping

Escape variable mysql password


I have a mysql password that starts with a space. I want to put this password into a variable and then use it to connect in a bash script.

this works fine:

mysql -u me -p' examplepw'

but this does not:

pw=" examplepw"
mysql -u me -p'$pw'

because the single quotes make the variable name be interpreted literally (ie. mysql does not recognise the string $pw as a valid password).

How can I use a variable to hold a mysql password that requires escaping?


Solution

  • ${} expands a variable.

    PASS=" 12345678"
    mysql -u me -p"${PASS}"
    

    In this case, ${PASS} is extended to 12345678