2012-03-04 84 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; 
相關問題