Linux 将查询存储在 bash 中的数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13843896/
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
Store query in array in bash
提问by Luca Davanzo
My script need to store in a structure the result of a query:
我的脚本需要将查询结果存储在一个结构中:
#!/bin/bash
user="..."
psw="..."
database="..."
query="select name, mail from t"
customStructure=$(mysql -u$user -p$psw $database -e "$query";)
I've no idea how store the array of {name, mail} from query result..
我不知道如何从查询结果中存储 {name, mail} 数组。
I need structure like this:
我需要这样的结构:
array=[ [name1,mail1] , [name2,mail2], ....., [nameN, mailN] ]
Is there a way to do this in bash?
有没有办法在 bash 中做到这一点?
采纳答案by Alex
Bash arrays are initialized like so:
Bash 数组初始化如下:
myarray=("hi" 1 "2");
To capture the individual portions of output of a command into an array, we must loop through the output, adding it's results to the array. That can be done like so:
要将命令输出的各个部分捕获到数组中,我们必须遍历输出,将其结果添加到数组中。可以这样做:
for i in `echo "1 2 3 4"`
do
myarray+=($i)
done
In your example, it looks like you wish to get the output of a MySQL command and store the parts of it's output lines into subarrays. I will show you how to capture lines into arrays, and given that, you should be able to figure out how to put subarrays into that yourself.
在您的示例中,您似乎希望获取 MySQL 命令的输出并将其输出行的一部分存储到子数组中。我将向您展示如何将行捕获到数组中,鉴于此,您应该能够弄清楚如何将子数组放入数组中。
while read line
do
myarray+=("$line")
done < <(mysql -u${user} -p${psw} ${database} -e "${query}")
It's also worth mentioning that for this kind of MySQL operation, where you don't need output metadata (such as pretty formatting and table names), you can use MySQL's -B
option to do 'batch output'.
还值得一提的是,对于这种不需要输出元数据(例如漂亮的格式和表名)的MySQL操作,可以使用MySQL的-B
选项进行“批量输出”。
回答by AzizSM
Field level record can be accessed via read -a
command and IFS
is set to the empty string to prevent read from stripping leading and trailing whitespace from the line.
字段级记录可以通过read -a
命令访问并IFS
设置为空字符串以防止读取从行中剥离前导和尾随空格。
#!/bin/bash
user="..."
psw="..."
database="..."
query="select name, mail from t"
OIFS="$IFS" ; IFS=$'\n' ; oset="$-" ; set -f
while IFS="$OIFS" read -a line
do
echo ${line[0]}
echo ${line[1]}
done < <(mysql -u${user} -p${psw} ${database} -e "${query}")