2012-03-04 87 views
47

我想仅在bash脚本中获得MySQL查询结果的值。例如,运行以下命令:如何从bash中的MySQL查询结果中获取字段

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

回报:

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

我怎样才能获取我的bash脚本返回的值?

回答

88

使用-s-N

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

the manual

--silent,-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-列名,-N

Do not write column names in results. 

编辑

貌似-ss作品以及和更容易记住。

+0

到@柯基犬的答案类似,多列将制表符分隔。 –

+2

为避免输出错误,重定向stderr: 'id = \'mysql -uroot -ppwd -ss -e“SELECT id FROM nagios.host WHERE name ='$ host'”2>/dev/null \'' –

+0

如何获取多列? – Deckard

1

尝试:

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

-B将利用标签作为列分离器和

--column-名称= 0将禁止标头打印结果。

1

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

在我的情况的解决方案是:

#!/bin/sh 

FIELDVALUE=$(mysql -ss -N -e "SELECT field FROM db.table where fieldwhere = '$2'") 

echo $FIELDVALUE 
4

更加紧凑:

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