How to avoid string value returned as part of sql query output being split into different fields in array in bash/shell script

The output of my sql query has multiple columns and contains string values which contains space. I need to write bash script where in i have to read values into variable and then use it further in the script also insert them into another database.

When i store output into an array the string value gets split based on space and stored into different indexes in array. How can i handle this situation in bash script.

CMD="SELECT * FROM upload where upload_time>='2020-11-18 00:19:48' LIMIT 1;"
output=($(mysql $DBCONNECT --database=uploads -N --execute="$CMD"))
echo ${output[9]}

version test_id upload_time parser_result 25 567 2020-11-18 00:19:48 <p1>box crashed with exit status 0</p1>

The upload time “2020-11-18 00:19:48” gets stored in two indexes.
The more problematic is ‘parser_result’ value which is string. '<p1>box crashed with exit status 0</p1>' gets stored in different indexes splitting based on space.

${output[8]} contains '<p1>box'
${output[9]} contains 'crashed'

Database is very huge and i need to parse every row in it.
Since string value can be anything i am unable come up with generic code. What is the best way to handle this scenario. Am using bash scripting for the first time!! I have to use bash script since this script will run as a cron job inside docker container.


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

The fields are separated by TAB. Use that as your $IFS to parse the result.

IFS=$'t' output=($(mysql $DBCONNECT --database=uploads -N --execute="$CMD"))
echo "${output[9]}"

If $DBCONNECT contains options separated with spaces, you need to do this in two steps, since it’s using $IFS to split that as well.

result=$(mysql $DBCONNECT --database=uploads -N --execute="$CMD")
IFS=$'t' output=($result)
echo "${ouptut[9]}"

All methods was sourced from or, 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