Splitting mysql query output into variables

I’m trying using shell script, to split mysql query output and save it in variables. My code looks like this:

read -ra tokens<<<$(mysql -u root -p'password' -D'users_info' -se 'SELECT token FROM users_logs')
for i in "${tokens[@]}"; do
        echo $i
var=$(mysql -u root -p'password' -D'users_info' -se 'SELECT token FROM users_logs')
echo $var

and script output:

2z7bhxbk7egquokj855d3 we3cq1d95drdq3micu9cn we3cq1d95drdq3micu9cn

As you can see, query result is the bottom one and it contains 3 tokens, but when I’m trying to split, it returns only first one. I think that, it’s delimiter fault, but I don’t really know what delimiter is used here, if not space.
Can anyone help me please?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

read should have no trouble with tabs. I suspect the issue is really the newlines – one line, one read. Try it this way –

while read -r t; do
  echo "${tokens[@]" # should show them accumulating
done < <(mysql -u root -p'password' -D'users_info' -se 'SELECT token FROM users_logs')


$: while read -r t; do tokens+=("$t"); echo "${tokens[@]}"; done < <( printf "%sn" a b c  )
a b
a b c

Whereas, what you are doing is basically this:

$: read -ra t < <( printf "%sn" a b c d e f g ) # only reads 1st line
$: echo "${#t[@]} ${t[@]}"
1 a

In this specific case…

You could probably use an otherwise bad-habit direct assignment to an array.

tokens=( $(mysql -u root -p'password' -D'users_info' -se 'SELECT token FROM users_logs') )

But don’t, unless you are going to add some data checking in your query. This is generally a horrible habit for several reasons, even if those tokens shouldn’t have any embedded whitespace.

The way you are doing it is better. You just need a read per line.

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x