2

I am storing output of MySQL query in a varible using shell scripting. The output of SQL query is in multiple rows. When I checked the count of the variable (which I think is an array), it is giving 1. My code snippet is as follows:

sessionLogin=`mysql  -ugtsdbadmin -pgtsdbadmin -h$MYSQL_HOST -P$MYSQLPORT CMDB -e " select distinct SessionID  div 100000 as 'MemberID' from SessionLogin where ClientIPAddr  like '10.104%' and LoginTimestamp > 1426291200000000000 order by 1;"`

echo "${#sessionLogin[@]}"

How can I store the MySQL query output in an array in shell scripting?

1 Answer 1

5

You can loop over the output from mysql and append to an existing array. For example, in Bash 3.1+, a while loop with process substitution is one way to do it (please replace the mysql parameters with your actual command)

output=()
while read -r output_line; do
    output+=("$output_line")
done < <(mysql -u user -ppass -hhost DB -e "query")
echo "There are ${#output[@]} lines returned"

Also take a look at the always excellent BashFaq

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.