2

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]}
2
  • Could you provide some examples of info_tmp variable? Commented Sep 2, 2013 at 9:55
  • 1
    @Aleks-DanielJakimenko The problem is that when one of the columns in the database is an empty string, bash just sees a pair of TAB characters, which is treated as one delimiter rather than two delimiters around an empty value. Commented Sep 2, 2013 at 10:02

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank You @Barmar, it seems it works, I can loop through $info_tmp for i in $info_tmp ; do echo $i ; done but I can't access to the array elements like echo ${info_tmp[1]} How can I access the individual elements?
When I tested this, I didn't have any problem accessing ${info_tmp[1]}.
This way works: After your code info=(${info_tmp// / }) Then ${info[1]} is info1
0

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-)

1 Comment

The problem is in the assignment to info_tmp, not info.

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.