2

I currently have a bash script where I want to separate the command to be executed from the execution itself (for readability purposes):

set -x
MAIN_COMMAND="mysql -u root \"select 1 from dual;\""
...
MAIN_RESULT=$($MAIN_COMMAND 2>&1)

when executing the command, I get the following debug output:

++mysql -u root '"select' 1 from 'dual;"'

obviously, there's something wrong with the way I escaped the string, but I can't pinpoint it.

furthermore the output redirection does not get concatenated to the main command.

E. Jaep
  • 2,095
  • 1
  • 30
  • 56
  • @tripleee: I was searching for an exact duplicate involving `mysql` in a variable. Thought it be useful. – Inian Oct 12 '18 at 12:32
  • Do `cmd=(mysql -u root "select 1 from dual;"); result=$( "${cmd[@]}" 2>&1)` – Inian Oct 12 '18 at 12:32
  • the extra quoting you are seeing is just the way the shell "normalizes" its output. Yes, it makes it hard to understand where the problem is, but if you're certain you're quoting is correct inside you script, then you can assume what is being displayed is correct (sorry I can't explain it logically, but there is a logical explanation ;-) ). To convince yourself this is the case, do some experimenting on the command with with `set -x` active. Good luck. – shellter Oct 12 '18 at 12:39
  • @Inian your duplicated mark do not include the origin of the question – PaulRM Oct 12 '18 at 12:53
  • @PaulRM: Agreed but the context is the same – Inian Oct 12 '18 at 12:54

1 Answers1

-1

Ok, try with:

set -x
MAIN_COMMAND="mysql -u root \"select 1 from dual;\""
MAIN_RESULT=$("$MAIN_COMMAND" 2>&1)

But, this only fix the escape part,

to the complete result, I use something like:

 set -x
 MAIN_COMMAND="MYSQL_PWD=dbpass /usr/bin/mysql -u dbuser dbname <<< \"select 1 from dual;\""
 MAIN_RESULT=$(eval "$MAIN_COMMAND" 2>&1)
PaulRM
  • 389
  • 4
  • 13
  • I end up with: mysql command not found... – E. Jaep Oct 12 '18 at 12:31
  • Yes, that part is an expected result. Too fix complety set -x MAIN_COMMAND="MYSQL_PWD=dbpass /usr/bin/mysql -u dbuser dbname <<< \"select 1 from dual;\"" MAIN_RESULT=$(eval "$MAIN_COMMAND" 2>&1) – PaulRM Oct 12 '18 at 12:43
  • Yes thanks. it also close to the solution I found here: https://stackoverflow.com/questions/18219262/evaluating-variables-in-a-string – E. Jaep Oct 12 '18 at 13:06