我想在bash脚本中只获取MySQL查询结果的值。例如,运行以下命令:
mysql -uroot -ppwd -e "SELECT id FROM nagios.host WHERE name='$host'"
返回:
+----+
| id |
+----+
| 0 |
+----+
如何获取bash脚本中返回的值?
答案 0 :(得分:101)
使用-s
和-N
:
> id=`mysql -uroot -ppwd -s -N -e "SELECT id FROM nagios.host WHERE name='$host'"`
> echo $id
0
来自the manual:
- 沉默,-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
也很有效,而且更容易记住。
答案 1 :(得分:7)
更紧凑:
id=$(mysql -uroot -ppwd -se "SELECT id FROM nagios.host WHERE name=$host");
echo $id;
答案 2 :(得分:1)
尝试:
mysql -B --column-names=0 -uroot -ppwd -e "SELECT id FROM nagios.host WHERE name='$host'"
-B将使用tab作为列分隔符和
打印结果- column-names = 0将禁用标题。
答案 3 :(得分:1)
我尝试了解决方案但总是收到空的回复。
就我而言,解决方案是:
#!/bin/sh
FIELDVALUE=$(mysql -ss -N -e "SELECT field FROM db.table where fieldwhere = '$2'")
echo $FIELDVALUE