3

I know there's some way to run bash command during redirect, but I don't know how exactly it is done.

I want to do something like this:

#!/bin/bash
mysql -uUser -pPasswd << EOF
echo 'I wanna echo something by using echo which is run by bash'
use Mydb
some sql commands here
commit;
EOF

I had ever done that by mistake by using " in the "<< EOF" , but failed to make it now.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Blangero
  • 115
  • 1
  • 1
  • 10
  • That is the correct syntax, as far as I can tell. – merlin2011 Jun 29 '14 at 04:48
  • It seems more likely that you are missing some `;` in your MySQL command. – merlin2011 Jun 29 '14 at 04:50
  • @merlin2011 since quotes might be confusing, I'll use system command, it's so clear. Sorry for missing the ';' , I just post too hurry. – Blangero Jun 29 '14 at 05:32
  • @ruakh sorry for my bad English. I want to run echo(bash) command besides(is this the correct word) a lot of mysql commands, to show the process of mysql commands. – Blangero Jun 29 '14 at 05:34

2 Answers2

6

You can use system command from within the mysql command line client:

#!/bin/bash
mysql -uUser -pPasswd << EOF
system echo 'I wanna echo something by using echo which is run by bash';
use Mydb
some sql commands here
commit;
EOF
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

In addition to using a heredoc to interact with MySQL from bash, you can simply call mysql itself in batch mode. This is useful when you have reasonably short queries and will eliminate needing to call system from within the heredoc body. The general form in bash is:

$(mysql -uuser -hhost database.table -Bse "any valid mysql command")

(you may omit .table if it is identified in your query) To handle the information returned by mysql, it is usually advisable to return the information to an array:

results=( $(mysql -uuser -hhost database.table -Bse "any valid mysql command") )

In that regard, you can structure your scripts in a more flexible manner.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85