bash 如何在重定向<<EOF期间运行bash命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24473216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run bash command during redirect << EOF
提问by Blangero
I know there's some way to run bash command during redirect, but I don't know how exactly it is done.
我知道有一些方法可以在重定向期间运行 bash 命令,但我不知道它究竟是如何完成的。
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.
我曾经错误地通过在 "<< EOF" 中使用 " 来做到这一点,但现在没能做到。
回答by anubhava
You can use system
commandfrom within the mysql
command line client:
您可以在命令行客户端中使用system
命令mysql
:
#!/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
回答by David C. Rankin
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:
除了使用 heredoc 从 bash 与 MySQL 交互之外,您还可以简单地以批处理模式调用 mysql 本身。当您有相当短的查询时,这很有用,并且不需要从 heredoc 正文中调用系统。bash中的一般形式是:
$(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:
(.table
如果在你的查询中被识别,你可以省略)为了处理 mysql 返回的信息,通常建议将信息返回到一个数组:
results=( $(mysql -uuser -hhost database.table -Bse "any valid mysql command") )
In that regard, you can structure your scripts in a more flexible manner.
在这方面,您可以以更灵活的方式构建脚本。