bash 数组循环没有返回正确的元素

bash array loop is not returning correct elements

这是我的 script.sh:

emails=$(curl -X GET http://0.0.0.0:5000/v1/user/all | jq 'map(.[].email)')
echo $emails
for email in ${emails[@]}
do
  echo $email
  FROM=$(date +"%Y-%m-%d %T")
  TO=$(date -d "$today -1 month" "+%Y-%m-%d %T")
  SEND=true
  JSON_STRING='{"email":"'"$email"'","from":"'"$FROM"'","to":"'"$TO"'","send":"'"$SEND"'"}'
  curl -X POST http://0.0.0.0:5000/v1/invoice/print -d JSON_STRING
done

我从第一次 API 调用中获得的电子邮件数据如下:

["email1@gmail.com", "email2@gmail.com", "email3@qbknowsfq.com"]

API POST curl 这样做:

{"email":"[","from":"2022-03-28 09:59:06","to":"2022-02-28 09:59:06","send":"true"}
{"message": "Internal Server Error"}
{"email":""email1@gmail.com",","from":"2022-03-28 09:59:06","to":"2022-02-28 09:59:06","send":"true"}
{"message": "Internal Server Error"}
{"email":""email2@gmail.com",","from":"2022-03-28 09:59:06","to":"2022-02-28 09:59:06","send":"true"}
{"message": "Internal Server Error"}
{"email":""email3@qbknowsfq.com",","from":"2022-03-28 09:59:06","to":"2022-02-28 09:59:06","send":"true"}
{"message": "Internal Server Error"}
{"email":"]","from":"2022-03-28 09:59:07","to":"2022-02-28 09:59:07","send":"true"}
{"message": "Internal Server Error"}

编辑:脚本回显 return:

["email1@gmail.com", "email2@gmail.com", "email3@qbknowsfq.com"]
[
{"email":"[","from":"2022-03-28 09:59:06","to":"2022-02-28 09:59:06","send":"true"}
{"message": "Internal Server Error"}
"email1@gmail.com",
{"email":""email1@gmail.com",","from":"2022-03-28 09:59:06","to":"2022-02-28 09:59:06","send":"true"}
{"message": "Internal Server Error"}
"email2@gmail.com",
{"email":""email2@gmail.com",","from":"2022-03-28 09:59:06","to":"2022-02-28 09:59:06","send":"true"}
{"message": "Internal Server Error"}
"email3@qbknowsfq.com",
{"email":""email3@qbknowsfq.com",","from":"2022-03-28 09:59:06","to":"2022-02-28 09:59:06","send":"true"}
{"message": "Internal Server Error"}
]
{"email":"]","from":"2022-03-28 09:59:07","to":"2022-02-28 09:59:07","send":"true"}
{"message": "Internal Server Error"}

我不明白为什么电子邮件循环处理括号 [ 和 ] 和 returning '"email@gmail.com",' 而不仅仅是 'email@gmail.com'?我做错了什么?

这是您从 jq 获得的输出:

[
    "email1@gmail.com",
    "email2@gmail.com",
    "email3@qbknowsfq.com",
]

bash-wise,不是数组,是multi-line字符串

[@] 索引它不会改变任何内容 returns 整个字符串。使用 for var in $multiline_string 对其进行迭代会为字符串的每个 space-separated 标记执行代码。由于您的电子邮件不包含空格,因此字符串的每一行都是如此。

您需要 jq 生成 space-separated 不带引号的电子邮件地址列表,以便 bash 轻松处理它们。只需将您的 jq 命令更改为以下内容:

jq -r 'map(.[].email)[]'