如何从bash中的MySQL查询结果中获取字段

我想在bash脚本中只获取MySQL查询结果的值。 例如运行以下命令:

mysql -uroot -ppwd -e "SELECT id FROM nagios.host WHERE name='$host'" 

收益:

 +----+ | id | +----+ | 0 | +----+ 

我如何获取在我的bash脚本中返回的值?

使用-s-N

 > id=`mysql -uroot -ppwd -s -N -e "SELECT id FROM nagios.host WHERE name='$host'"` > echo $id 0 

从手册 :

– 无声的,-s

  Silent mode. Produce less output. This option can be given multiple times to produce less and less output. This option results in nontabular output format and escaping of special characters. Escaping may be disabled by using raw mode; see the description for the --raw option. 

–skip-column-names,-N

  Do not write column names in results. 

编辑

看起来像-ss也很容易记住。

更紧凑:

 id=$(mysql -uroot -ppwd -se "SELECT id FROM nagios.host WHERE name=$host"); echo $id; 

尝试:

 mysql -B --column-names=0 -uroot -ppwd -e "SELECT id FROM nagios.host WHERE name='$host'" 

-B将打印结果使用选项卡作为列分隔符和

–column-names = 0将禁用标题。

我尝试了解决scheme,但总是收到空的答复。

在我的情况下,解决scheme是:

 #!/bin/sh FIELDVALUE=$(mysql -ss -N -e "SELECT field FROM db.table where fieldwhere = '$2'") echo $FIELDVALUE