bash - Bash循环一个curl请求,输出到文件并停止直到空响应
问题描述
所以我有以下 bash 文件,现在它基于 for 循环循环一个 curl 请求。但是,我想知道如何继续循环直到响应为空。
不幸的是,我调用的 API 是基于每页最多响应 500 个结果的页面。我试图提取自 2017 年以来的数据,所以它有很多数据。
我想继续反击,直到响应为空。
#!/bin/bash
# Basic while loop
counter=1
for ((i=1;i<=2;i++));
do
curl -o gettext.txt --request GET \
--url "https://api.io/v1/candidates?page=${counter}&per_page=500" \
--header 'Authorization: Basic aklsjdl;fakj;l;kasdflkaj'
((counter++))
done
echo $counter
echo All done
有人有想法吗?
解决方案
正如作者对他/她自己的帖子的评论所述,返回的数据是 json 格式。作者没有问如何追加两个json文件,但这是他/她完成工作的必要步骤。为了附加两个 json,json1 和 json2,也许跳过 json1 last byte}
和 json2 first byte {
,,
在它们之间追加就足够了。在这里,我使用jq
连接两个 json 作为更通用的方法。
在下面显示的示例中,该nextjsonchunk
文件是每次请求时获取的 json 文件。如果它有内容,则将其附加到mainjsonfile
with jq
。如果它看起来是空的(由它的大小推断),循环中断,结果被移动到当前文件夹并进行清理。
使用curl
:
#!/usr/bin/env bash
tempfolder=/dev/shm # temporary memory parition, avaiable in ubuntu
emptyjsonize=10 # the minimum json file length, to be used as a threshold
for ((counter=1; 1; counter++))
do
curl "https://api.io/v1/candidates?page=${counter}&per_page=500" \
--header "Authorization: Basic aklsjdl;fakj;l;kasdflkaj" \
--ouput $tempfolder/nextjsonchunk
if [ $(wc -c <$tempfolder/nextjsonchunk) -le $emptyjsonize ]; then break; fi
jq -s '.[0]*.[1]' $tempfolder/mainjsonfile $tempfolder/nextjsonchunk > $folder/mainjsonfile
done
rm $tempfolder/nextjsonchunk # cleaning up
mv $tempfolder/mainjsonfile ./jsonresultfile # end result
或者,使用wget
:
#!/usr/bin/env bash
tempfolder=/dev/shm # temporary memory parition, avaiable in ubuntu
emptyjsonize=10 # the minimum json file length, to be used as a threshold
for ((counter=1; 1; counter++))
do
wget "https://api.io/v1/candidates?page=${counter}&per_page=500" \
--header="Authorization: Basic aklsjdl;fakj;l;kasdflkaj" \
--ouput-document $tempfolder/nextjsonchunk
if [ $(wc -c <$tempfolder/nextjsonchunk) -le $emptyjsonize ]; then break; fi
jq -s '.[0]*.[1]' $tempfolder/mainjsonfile $tempfolder/nextjsonchunk > $folder/mainjsonfile
done
rm $tempfolder/nextjsonchunk # cleaning up
mv $tempfolder/mainjsonfile ./jsonresultfile # end result
获取两个样本 json 并测试它们之间的合并是一个好主意,以检查它是否正确完成。
确保空 json 文件检查是否正常也很好。10 个字节只是一个猜测。
示例中使用了
tmpfs
(内存中)分区,/dev/shm
以避免多次写入,但它的使用是可选的。
推荐阅读
- flutter - 颤振本地通知无法在单击时导航到另一条路线
- flutter - 如何将动态列表类型转换为飞镖中的多维类型列表?
- date - 计算日期是否在日期范围列表之间 - Google 表格
- flutter - 如何在 json key:value 中插入占位符?扑
- c++ - 如何治疗 N
作为 N ? - c - 以下c如何输出垃圾?
- c# - 如何从 C# 程序集生成摩纳哥完成建议?
- r - R中的时间序列连接散点图(如图所示)
- r - sass_options() 中的错误:找不到函数“strrep”
- python - 导入 python 模块在命令行中有效,但在 python 3.8 shell 中无效