views:

305

answers:

2

I try to execute the following command :

mysql AMORE -u username -ppassword -h localhost -e "SELECT  host  FROM amoreconfig"

I store it in a string :

cmd="mysql AMORE -u username -ppassword -h localhost -e\"SELECT  host  FROM amoreconfig\""

Test it :

echo $cmd
mysql AMORE -u username -ppassword -h localhost -e"SELECT host FROM amoreconfig"

Try to execute by doing :

$cmd

And I get the help page of mysql :

mysql  Ver 14.14 Distrib 5.1.31, for pc-linux-gnu (i686) using readline 5.1
Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL license
Usage: mysql [OPTIONS] [database]
(...)

I guess I am doing something plain wrong with the quotes but can't find out what is the problem.

Could you help me ?

Thanks in advance

+2  A: 

Have you tried:

eval $cmd

For the follow-on question of how to escape * since it has special meaning when it's naked or in double quoted strings: use single quotes.

MYSQL='mysql AMORE -u username -ppassword -h localhost -e'
QUERY="SELECT "'*'" FROM amoreconfig" ;# <-- "double"'single'"double"
eval $MYSQL "'$QUERY'"

Bonus: It also reads nice: eval mysql query ;-)

slebetman
Thanks, it works. How would I select all columns ? How can I escape '*' ?
Barth
You do not need to escape asterisk (*) in this case.
filiprem
Just use single quotes.
slebetman
first attempt with both failed. I had to use eval $MYSQL \"$QUERY\"But then the first one returns +---+| * |+---+| * |(...)And the second with the escaping fails with :ERROR at line 1: Unknown command '\*'.Thanks for your help anyway :)
Barth
Fixed. Not sure exactly how it works, just followed a hunch. Maybe another shell guru can explain.
slebetman
+1  A: 

try this

$ cmd='mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'
$ eval $cmd
ghostdog74
thanks, it works. I marked the other answer as the accepted one because it came before.
Barth