0

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.

2
  • That's just how a bash for loop works... you can't expect to have spaces inside fields that you're delimiting with spaces. Commented Jul 23, 2013 at 18:35
  • @CarlNorum:So how should I handle res which is the result set of mysql? Commented Jul 23, 2013 at 18:37

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.