0

I'm constructing a Bash script to execute a MySQL query. The Bash scrip is very simple, but the query is not being executed correctly. MySQL responds like a do a mysql usage (help of commands). What am I doing wrong?

The bash file is:

COMANDO='mysql -h 148.72.64.68 -p******** -u root db_vias_ue -e "select count(*) from clientes"'

$COMANDO
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Rabelo
  • 57
  • 4
  • you say a simple script, yet your complicating it for no good reason (that is apparent). Just run the cmd from your file. FIrst line : `#!/bin/bash`, 2nd line: `mysql -h .......` ... End of script, done! ;-)! Good luck. – shellter Nov 16 '21 at 18:34
  • There are literally a 1000+ Q/A when you search for `[bash] mysql script`. Look at https://stackoverflow.com/questions/25135661/linux-shell-script-catching-exit-code-after-executing-mysql-script-shell for an more advanced example (but well constructed) of using `mysql` in a `bash` script. Good luck. – shellter Nov 16 '21 at 18:40
  • Don't store commands in variables; variables are for data, not executable code. See [BashFAQ #50: "I'm trying to put a command in a variable, but the complex cases always fail!"](http://mywiki.wooledge.org/BashFAQ/050) and [many](https://stackoverflow.com/questions/5615717) [previous](https://stackoverflow.com/questions/29527983) [questions](https://stackoverflow.com/questions/13365553) (but avoid all suggestions involving `eval` -- that way lies madness and weirder bugs). – Gordon Davisson Nov 16 '21 at 18:50
  • Just to justify the weirdness: I cut up all that would interfier in the question, trying to be as much as foused on the problem as possible. Why it is doing this way? Is a long story... thank you for your comments and advices! – Rabelo Nov 16 '21 at 20:21

1 Answers1

0

Bash quoting rules are seriously weird. In what you wrote, the expression within double quotes actually gets separated into multiple arguments.

Try this:

COMANDO='mysql -h 148.72.64.68 -p******** -u root db_vias_ue -e "select count(*) from clientes"'

bash -c "$COMANDO"
cidermole
  • 5,662
  • 1
  • 15
  • 21
  • This has most of the same problems as `eval`, and is generally a bad idea. Depending on the actual goal, there's almost certainly a better solution. – Gordon Davisson Nov 16 '21 at 18:52