Zoltan
Zoltan

Reputation: 513

Bash mysql array do not get empty value

My Bash script makes an array from MySQL:

info_tmp=$(mysql --batch --silent -u root -ppassword database -e "SELECT id,info1,info2 FROM table WHERE id=1")
info=($(for i in $info_tmp;do echo $i;done))
info1=${info[1]}

My problem is, that, if info1 is an empty string in the database, then $info1 became info2. How can I put an empty string into $info array?

Mysql Database: 
Id | info1 | info2 
 1 |       | data2 
 2 | data3 | data4 

$info_tmp 
1 data2 
2 data3 data4

Thank you for your answer

This is the final code that worked (@Barmar):

IFS="|"
info_tmp=$(mysql --batch --silent -u root -ppassword database -e "SELECT CONCAT_WS('|', id,info1,info2) FROM table WHERE id=1")
info=(${info_tmp// / })
info1=${info[1]}

Upvotes: 2

Views: 1224

Answers (2)

Barmar
Barmar

Reputation: 781096

If there's a character that shouldn't appear in any of the columns, use that as a delimiter.

IFS="|"
info_tmp=$(mysql --batch --silent -u root -ppassword database -e "SELECT CONCAT_WS('|', id,info1,info2) FROM table WHERE id=1")

This works because bash doesn't merge sequences of non-whitespace delimiters in IFS, only whitespace characters.

I'm not sure what the point of the for loop that copies $info_tmp to $info is, but you need to do the same thing there. If you use whitespace as your word delimiter, you'll never be able to get empty array values from command substitution.

Upvotes: 1

cutsoy
cutsoy

Reputation: 10251

What about temporarily adding a single character in your for-loop:

info_tmp=$(mysql --batch --silent -u root -ppassword database -e "SELECT id,info1,info2 FROM table WHERE id=1")
info=($(for i in $info_tmp;do echo " "$i;done))
info1=$(${info[1]} | cut -c 2-)

Upvotes: 0

Related Questions