如何在shell脚本中转​​换数组中的MySQL查询输出?

Tus*_* R. 2 mysql arrays shell

我使用shell脚本将MySQL查询的输出存储在varible中.SQL查询的输出是多行.当我检查变量的计数(我认为是一个数组)时,它给出了1.我的代码片段如下:

sessionLogin=`mysql  -ugtsdbadmin -pgtsdbadmin -h$MYSQL_HOST -P$MYSQLPORT CMDB -e " select distinct SessionID  div 100000 as 'MemberID' from SessionLogin where ClientIPAddr  like '10.104%' and LoginTimestamp > 1426291200000000000 order by 1;"`

echo "${#sessionLogin[@]}"
Run Code Online (Sandbox Code Playgroud)

如何在shell脚本中将MySQL查询输出存储在数组中?

Fre*_*sen 5

您可以循环mysql的输出并附加到现有数组.例如,在Bash 3.1+中,带有进程替换的while循环是一种方法(请用你的实际命令替换mysql参数)

output=()
while read -r output_line; do
    output+=("$output_line")
done < <(mysql -u user -ppass -hhost DB -e "query")
echo "There are ${#output[@]} lines returned"
Run Code Online (Sandbox Code Playgroud)

另外,看看总是优秀的BashFaq