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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9558867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 12:21:48  来源:igfitidea点击:

How to fetch field from MySQL query result in bash

mysqlbash

提问by Nachshon Schwartz

I would like to get only the value of a MySQL query result in a bash script. For example the running the following command:

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

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

returns:

返回:

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

How can I fetch the value returned in my bash script?

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

回答by Dor Shemer

Use -sand -N:

使用-s-N

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

From 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-column-names, -N

   Do not write column names in results.

--沉默,-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.

EDIT

编辑

Looks like -ssworks as well and much easier to remember.

看起来也-ss有效,而且更容易记住。

回答by Pratik Patil

Even More Compact:

更紧凑:

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

回答by Finbar Crago

Try:

尝试:

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

-B will print results using tab as the column separator and

-B 将使用制表符作为列分隔符打印结果,并且

--column-names=0 will disable the headers.

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

回答by Marcelo Amorim

I tried the solutions but always received empty response.

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

In my case the solution was:

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

#!/bin/sh

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

echo $FIELDVALUE