How to fetch field from MySQL query result in bash

MysqlBash

Mysql Problem Overview


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

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?

Mysql Solutions


Solution 1 - Mysql

Use -s and -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.

EDIT

Looks like -ss works as well and much easier to remember.

Solution 2 - Mysql

Even More Compact:

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

Solution 3 - Mysql

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

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

Solution 4 - Mysql

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 = '$2'")

echo $FIELDVALUE

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNachshon SchwartzView Question on Stackoverflow
Solution 1 - MysqlDor ShemerView Answer on Stackoverflow
Solution 2 - MysqlPratik PatilView Answer on Stackoverflow
Solution 3 - MysqlFinbar CragoView Answer on Stackoverflow
Solution 4 - MysqlMarcelo AmorimView Answer on Stackoverflow