14

My script need to store in a structure the result of a query:

 #!/bin/bash
 user="..."
 psw="..."
 database="..."
 query="select name, mail from t"
 customStructure=$(mysql -u$user -p$psw $database -e "$query";)

I've no idea how store the array of {name, mail} from query result..

I need structure like this:

 array=[ [name1,mail1] , [name2,mail2], ....., [nameN, mailN] ]

Is there a way to do this in bash?

1
  • why bash? u can use others language like php, python, ruby to do the same job, and probably is much easier Commented Dec 12, 2012 at 16:19

2 Answers 2

17

Bash arrays are initialized like so:

myarray=("hi" 1 "2");

To capture the individual portions of output of a command into an array, we must loop through the output, adding it's results to the array. That can be done like so:

for i in `echo "1 2 3 4"`
do
    myarray+=($i)
done

In your example, it looks like you wish to get the output of a MySQL command and store the parts of it's output lines into subarrays. I will show you how to capture lines into arrays, and given that, you should be able to figure out how to put subarrays into that yourself.

while read line
do 
    myarray+=("$line")
done < <(mysql -u${user} -p${psw} ${database} -e "${query}")

It's also worth mentioning that for this kind of MySQL operation, where you don't need output metadata (such as pretty formatting and table names), you can use MySQL's -B option to do 'batch output'.

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

1 Comment

No problem, I'm really happy I was able to help! If you'd like to learn more about Bash array's on your own check out the examples here: tldp.org/LDP/abs/html/arrays.html
3

Field level record can be accessed via read -a command and IFS is set to the empty string to prevent read from stripping leading and trailing whitespace from the line.

#!/bin/bash
user="..."
psw="..."
database="..."
query="select name, mail from t"

OIFS="$IFS" ; IFS=$'\n' ; oset="$-" ; set -f

while IFS="$OIFS" read -a line 
do 
  echo ${line[0]}   
  echo ${line[1]}   
done < <(mysql  -u${user} -p${psw} ${database} -e "${query}")

2 Comments

Doesn't work with spaces in returned values, as they will be split into separate items of the array by read -a.
Also the first line will be the column names. not the cleanest, but better would be to add: | sed 's# #_#g' | sed 1d

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.