Rafael Osuna Dominguez
Rafael Osuna Dominguez

Reputation: 479

Bash script: Mysql query field to variable

I'm trying to obtain a recordset and read a few fields from it. I'm not able to figure it out how put the fields into variables. The script is:

#!/bin/bash
sqlQuery="$(mysql -h host -u user -ppass -D oberonsaas_v2 -s -N -e 
'select ventas.id_venta,
ventas_entradas.id_ventas_entradas,
ventas.id_evento,
id_tarifa,
DATE_FORMAT(fecha_evento,"%Y%m%d") as fecha,
TIME_FORMAT(pase,"%H%i") as pase

from pases,ventas,ventas_entradas,recintos

where ventas.id_recinto = recintos.id_recinto 
and ventas.id_pase = pases.id_pase
and ventas.id_venta = ventas_entradas.id_venta
and recintos.id_cliente = 32
and ventas.estado="Pagada"
and date(fecha_venta) = date_add(date(CURRENT_TIMESTAMP),INTERVAL -1 day)')"
echo $sqlQuery

I get all the recordset in $sqlQuery, but i want to do a loop and concat the fields.

Upvotes: 0

Views: 4182

Answers (2)

FrankBoller
FrankBoller

Reputation: 153

Collapse this into the simplest possible construct. Put returned recordset into a bash array (for example):

sqlQuery=( pases_value ventas_value ventas_entradas_value recintos_value )

note: yours could look like:

sqlQuery=( $(mysql -h host ... )

new lines between the array operators "(" and ")" are ok

each will be in a distinct sqlQuery array location. for example return: recintos_value

echo ${sqlQuery[3]}

concat all:

echo ${sqlQuery[*]}

if delimiters are of concern, use the mysql --delimiter switch to define a desired character, then

set concatValue=${sqlQuery[*]}

then to remove the delimiter character ("," for example):

set finalValue=${concatValue//,}

Upvotes: 0

X Tian
X Tian

Reputation: 772

Well I have invented some output

#!/bin/bash

Result="21,336,purchase,tarif_exspensive,Jose"
(IFS=","
for i in $Result
do
    echo "I Have: " $i
done
)

Ouput is

$ bash t5.sh 
I Have:  21
I Have:  336
I Have:  purchase
I Have:  tarif_exspensive
I Have:  Jose

Upvotes: 1

Related Questions