mulllhausen
mulllhausen

Reputation: 4435

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?

Upvotes: 1

Views: 1654

Answers (3)

Mureinik
Mureinik

Reputation: 311163

As long as you're using environment variables, you could store the password in MYSQL_PWD. MySQL will just take it from there:

export MYSQL_PWD=" examplepw"
mysql -u me

Upvotes: 1

Shahriar
Shahriar

Reputation: 13804

${} expands a variable.

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

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

Upvotes: 0

mulllhausen
mulllhausen

Reputation: 4435

Ah I just found the solution: terminate the single quote, and concatenate the variable quoted with double quotes:

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

Upvotes: 1

Related Questions