Bash:如何调用命令并将结果存储在变量中?

时间:2022-04-11 05:52:48

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“从table1中选择count(*)”。然后获取此命令结果(该表上的计数)并将其放在bash脚本中的变量中。实现这一目标的最简单方法是什么?

2 个解决方案

#1


40  

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";)

#2


14  

$ A=$(mysql -uanon -ppwd -db mydb -e "select count(*) from table1")
$ echo $A

In other words, use the $() syntax.

换句话说,使用$()语法。

#1


40  

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";)

#2


14  

$ A=$(mysql -uanon -ppwd -db mydb -e "select count(*) from table1")
$ echo $A

In other words, use the $() syntax.

换句话说,使用$()语法。