Bash - 只有在出现新行时才去下一个索引,而不是白色 space?

Bash - Only go next index when new line occurs, instead of white space?

我正在使用名为 jq 的工具解析 JSON 响应。 jq 的输出将在我的命令行中提供全名列表。

我有包含 JSON 的变量 getNames,例如:

{
    "count": 49,
    "user": [{
        "username": "jamesbrown",
        "name": "James Brown",
        "id": 1
    }, {
        "username": "matthewthompson",
        "name": "Matthew Thompson",
        "id": 2
    }]
}

我通过 JQ 传递它以使用以下命令过滤 json:

echo $getNames | jq -r .user[].name

这给了我一个这样的列表:

James Brown   
Matthew Thompson   

我想将这些条目中的每一个都放入一个 bash 数组中,所以我输入以下命令:

declare -a myArray    
myArray=( `echo $getNames | jq -r .user[].name` )

但是,当我尝试使用以下方法打印数组时:

printf '%s\n' "${myArray[@]}"

我得到以下信息:

James
Brown
Matthew
Thompson

如何确保在新行之后创建新索引而不是 space?为什么名字要分开?

谢谢。

只需使用 mapfile 命令将多行读入数组,如下所示:

mapfile -t myArray < <(jq -r .user[].name <<< "$getNames")

bash 中的一个简单脚本,用于将输出的每一行输入数组 myArray

#!/bin/bash

myArray=()
while IFS= read -r line; do
    [[ $line ]] || break  # break if line is empty
    myArray+=("$line")
done < <(jq -r .user[].name <<< "$getNames")

# To print the array
printf '%s\n' "${myArray[@]}"