How to run bash command during redirect << E

2019-07-04 06:22发布

问题:

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.

回答1:

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


回答2:

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.