MySQL Bash:如何调用命令并将结果存储在变量中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2730766/
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
Bash: How to invoke command and store the result in a variable?
提问by Zombies
Basically I want to be able to invoke a given command, in this case mysql -uanon -ppwd -db mydb -e "select count(*) from table1"
. And then take this commands result (the count on that table) and place it in a variable in bash script. What is the simplest way to achieve this?
基本上我希望能够调用给定的命令,在这种情况下mysql -uanon -ppwd -db mydb -e "select count(*) from table1"
。然后获取此命令结果(该表上的计数)并将其放入 bash 脚本中的变量中。实现这一目标的最简单方法是什么?
回答by Jürgen H?tzel
You most likely want to use batch mode (-B) and disable column names (--disable-column-names) for non-interactive mysql output:
您很可能希望使用批处理模式 (-B) 并禁用非交互式 mysql 输出的列名 (--disable-column-names):
out=$(mysql -B -db mydb -uanon -ppwd --disable-column-names -e "select count(*) from table1";)
回答by unwind
$ A=$(mysql -uanon -ppwd -db mydb -e "select count(*) from table1")
$ echo $A
In other words, use the $() syntax.
换句话说,使用 $() 语法。