I need to store in array the results retrieved from the database. So far this is basically what I'm trying with no success.

 Myarray=$(echo "SELECT A, B, C FROM table_a" | mysql database -u $user -p$password)

My understanding of bash commands is not very good as you can see. thank you.

  • What you have looks like a good start. What do you mean by "no success"? What happens when you do this? – G-Man Nov 21 '14 at 20:45
  • i have many error like 'mysql Ver 14.14 Distrib 5.5.40, for debian-linux-gnu (x86_64) using readline 6.3 Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Usage: mysql [OPTIONS] [database] -?, --help Display this help and exit. -I, --help Synonym for -? --auto-rehash Enable automatic rehashing. One doesn't need to use 'rehash' to get table and field completion – Fimo Nov 21 '14 at 21:00
  • So, does echo "SELECT A, B, C FROM table_a" | mysql database -u $user -p$password produce the results that you want to capture? If it doesn't, you need to get that working first, and then worry about the command substitution. – G-Man Nov 21 '14 at 21:19

This works:

results=($(mysql --user root -pwelcome ts -Bse "SELECT type, network_id, subnet_msk FROM remote_subnet;"))

for (( i=0 ; i<cnt ; i++ ))
    echo "Record No. $i: ${results[$i]}"
  • cnt=${#results[@]} is giving the number of characters in the returned output, not the number of lines. – crafter Jul 16 '18 at 11:56
#! bin/bash
query="select * from test;"

myarray=$(mysql -h hostname -u user -ppass database << eof

echo $myarray
  • 1
    Can you explain what this code does and how it solves the OP's problem? – bwDraco Nov 21 '14 at 21:40
  • Did you test this? Are you sure the myarray=$ should have a "$"? Are you making some assumptions about the format of the data being returned from the query? Bash only supports single dimensional arrays? How are you dealing with the rows and columns? This looks too easy. – Marianna Nov 21 '14 at 21:44
  • It does what he originally asked, store the result of the query in a bash variable. It didn't deal with neither rows nor columns. – jherran Nov 21 '14 at 21:50

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.