68

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?

4 Answers 4

133

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.

4
  • Similar to @corgi's answer, multiple columns will be tab delimited. Nov 9, 2012 at 3:29
  • 2
    To avoid getting errors as output, redirect stderr: id=`mysql -uroot -ppwd -ss -e "SELECT id FROM nagios.host WHERE name='$host'" 2> /dev/null` Nov 9, 2012 at 3:38
  • How to fetch multiple columns?
    – Deckard
    May 15, 2014 at 9:30
  • 1
    @Deckard $ set mysql -uroot -ppwd -ss -e "SELECT 'a','b'. Then the value of $1 should be "a" and $2 "b".
    – dorsh
    Oct 20, 2014 at 12:32
12

Even More Compact:

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

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.

2
  • thank you, this is helpful for creating a bash option list.
    – Artistan
    Jan 12, 2021 at 2:29
  • This is very useful as it shows how to return the result "without" the column name which is really useful when you are trying to set a variable.
    – Doug
    Feb 11, 2021 at 1:04
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.