Jim
Jim

Reputation: 19572

How can I efficiently handle the result set of mysql from a bash script?

I was excited to see how easy it is to write a bash script to interact with MySQL.
But trying this:

#!/bin/bash  

res=`mysql -u $USER -p$PASS students <<EOF | tail -n +2  
SELECT name FROM table WHERE age = 20 limit 1;  
EOF`  

for d in $res;  
do  
echo Result : $d  
done  

If the result is "John Smith" I get:
Result: John
Result: Smith

How can I get around this issue with the space?
It seems like it treats it as 2 values while it is a single column.

Upvotes: 0

Views: 669

Answers (1)

Lorenzo Marcon
Lorenzo Marcon

Reputation: 8169

One way to do what you ask is adding this before loop:

IFS=$'\n'

This will change default bash internal field separator (IFS), which by default works with spaces, tabs and new lines.

My example will only work with new lines, as probably this is what you're looking for.

Upvotes: 3

Related Questions