首页 > 解决方案 > 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

有人有想法吗?

标签: bashcurl

解决方案


正如作者对他/她自己的帖子的评论所述,返回的数据是 json 格式。作者没有问如何追加两个json文件,但这是他/她完成工作的必要步骤。为了附加两个 json,json1 和 json2,也许跳过 json1 last byte}和 json2 first byte {,在它们之间追加就足够了。在这里,我使用jq连接两个 json 作为更通用的方法。

在下面显示的示例中,该nextjsonchunk文件是每次请求时获取的 json 文件。如果它有内容,则将其附加到mainjsonfilewith 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以避免多次写入,但它的使用是可选的。


推荐阅读