0

Bash and MySQL versions:

GNU bash, version 4.2.25(1)-release (x86_64-pc-linux-gnu)
mysql  Ver 14.14 Distrib 5.5.37, for debian-linux-gnu (x86_64) using readline 6.2

I have a bash script that tries to capture the result of a MySQL query to a variable using command substitution with the MySQL password as a variable that contains a dollar sign and no matter which way I try it, it always either fails authentication with access denied message or the query returns the MySQL help command text. I've tried dozens of different combinations of both types of command substitution and escaping characters till the cows come home. Here is an example:

PASS='pass$word'; RESULT=`mysql -u user -p'${PASS}' -h RemoteHostName DBName -e "select count(*) from TableName;"`; echo "${RESULT}";

This will return "Access denied for user"...

PASS='pass$word'; RESULT=`mysql -u user -p\'${PASS}\' -h RemoteHostName DBName -e \"select count\(*\) from TableName\;\"`; echo "${RESULT}";

This will return the MySQL help text

Any help would be much appreciated, thanks in advance.

3
  • 1
    RESULT=$(mysql -u user -p "${PASS}" -h RemoteHostName DBName -e "select count(*) from TableName;") Will work as expected Commented Oct 9, 2014 at 14:52
  • 2
    You are correct, that works however this being my first post on this forum, I'm not entirely sure how to give you credit for the answer when you just replied with a comment.
    – Nathan
    Commented Oct 9, 2014 at 15:51
  • No problem, I'm not after getting credits really. I'm glad I could help. You can post my comment as answer an mark it as answer yourself. Commented Oct 10, 2014 at 7:34

2 Answers 2

2

val0x00ff's answer was correct in the comment section above

RESULT=$(mysql -u user -p "${PASS}" -h RemoteHostName DBName -e "select count(*) from TableName;")
0

You need to escape the password value, not its usage:

PASS="pass\$word"; RESULT=`mysql -u user -p'${PASS}' -h RemoteHostName DBName -e "select count(*) from TableName;"`; echo "${RESULT}";

As everything after the $ is being interpreted as a reference to a variable named $word

[user@host ~]$ echo "pass$word"
pass
[user@host ~]$ echo "pass\$word"
pass$word
1
  • Actually that was like the first thing I tried, that still results in "Access denied for user"...
    – Nathan
    Commented Oct 9, 2014 at 14:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .