Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch field from MySQL query result in bash

Tags:

bash

mysql

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?

like image 845
Nachshon Schwartz Avatar asked Mar 04 '12 21:03

Nachshon Schwartz


People also ask

How do I fetch a specific column in MySQL?

If you want to select only specific columns, replace the * with the names of the columns, separated by commas. The following statement selects just the name_id, firstname and lastname fields from the master_name table.

How do you assign a SQL query output to a variable in a shell script?

In first command you assign output of date command in "var" variable! $() or `` means assign the output of command. And in the second command you print value of the "var" variable. Now for your SQL query.


2 Answers

Even More Compact:

id=$(mysql -uroot -ppwd -se "SELECT id FROM nagios.host WHERE name=$host"); echo $id; 
like image 45
Pratik Patil Avatar answered Sep 16 '22 14:09

Pratik Patil


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.

like image 119
Dor Shemer Avatar answered Sep 19 '22 14:09

Dor Shemer