2

I am having a really difficult time figuring out how to get the results of a mysql query into a bash shell script variable.

testDBName="some_database_name"
mysqlUser="root"
mysqlPassword="password"
mysqlCmd="/Applications/MAMP/Library/bin/mysql -u $mysqlUser -p $mysqlPassword -B -N"
cmdRes=$($mysqlCmd -e 'SHOW DATABASES LIKE "$testDBName"') #THIS IS THE TROUBLESOME LINE
if [ "$cmdRes" = "" ]; then
    echo "Table does not exist"
else
    echo "Table already exists"
fi

The line that is giving me the trouble is "cmdRes=...". If I just hard-code a table name into that it works fine, like this:

cmdRes=$($mysqlCmd -e 'SHOW DATABASES LIKE "some_database_name"')

But I cannot wrap my head around how/why/what is going on when I have a $variable inside that thing. Based on answers to a lot of other similar-but-different questions, I've tried putting different portions of the string into different variables to cut down on quoting, I've tried single quotes, double quotes, backslashes, double-single-double quotes, curly braces, running eval, etc. -- but nothing is working.

Thanks for any help you can provide.

1 Answer 1

5

The problem is that the shell won't expand anything inside the single quotes (').

One possible solution:

cmdRes=$($mysqlCmd -e "SHOW DATABASES LIKE '$testDBName'")
Sign up to request clarification or add additional context in comments.

1 Comment

Wait, I just tried that without the backslashes and it works! If you edit your answer I'll mark it correct (I don't have edit priveleges). Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.