Bash 脚本和行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14932525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:35:35  来源:igfitidea点击:

Bash script and rows

mysqlarraysbash

提问by Unmerciful

my problem is with rows mysql_query. I need:

我的问题是行 mysql_query。我需要:

Record 0: 2,text is text,3.23

But I have:

但我有:

Record 0: 2
Record 1: text
Record 2: is
Record 3: text
Record 4: 3.23

Please help me.

请帮我。

results=($(mysql --user root -proot test -Bse "select id,name from Object"));

cnt=${#results[@]}

for (( i=0 ; i<${cnt} ; i++ ))
do
    echo "Record No. $i: ${results[$i]}"

    fieldA=${results[0]};
    fieldB=${results[1]};

done

回答by dogbane

The problem is that you are storing the output of mysqlinto an array. Now, if mysqlreturns multiple records you won't know when a record ends and the next one starts because the array will contain the "flattened" data e.g. ( record1_fieldA record1_fieldB record2_fieldA record2_fieldB ... )

问题是您将 的输出存储mysql到数组中。现在,如果mysql返回多条记录,您将不知道一条记录何时结束而下一条记录何时开始,因为该数组将包含“扁平化”数据,例如( record1_fieldA record1_fieldB record2_fieldA record2_fieldB ... )

Instead, use a whileloop to iterate over the records like this:

相反,使用while循环来迭代这样的记录:

i=0
while read fieldA fieldB
do
    echo "Record $(( i++ )): fieldA: $fieldA fieldB: $fieldB"
done < <(mysql --user root -proot test -Bse "select id,name from Object")