Bash 循环一个curl 请求,输出到文件并停止直到空响应

标签 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 最后一个字节 } 和 json2 第一个字节 {,并在它们之间附加 ,足够。在这里,我使用 jq 来连接两个 json,作为一种更通用的方法。

在下面的示例中,nextjsonchunk 文件是每次请求时获取的 json 文件。如果它有内容,则会使用 jq 将其附加到 mainjsonfile 中。如果它看起来是空的(根据其大小推断),则循环中断,结果将移动到当前文件夹并进行清理。

使用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,以避免多次写入,但其使用是可选的。

关于Bash 循环一个curl 请求,输出到文件并停止直到空响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65692591/

相关文章:

ruby-on-rails - Ruby 从 bash 脚本执行中捕获 stderr 输出

linux - shell 内的 shell 脚本 shell

python - 使用 python urllib2 访问 itop 数据库(通过 oql)

php - Symfony2 : no extension to load Buzz

php - 如何使用 cURL 签署使用 sfGuardUser 的 Symfony 项目?

node.js - URL 在浏览器中加载,但不在终端中加载(curl 或 Node.js)

ruby-on-rails - Docker: chmod: 无法访问 'chmod' : 没有这样的文件或目录

arrays - 使用 shell 变量选择一个 bash 数组

cURL命令Dload速度的单位?

linux - 将参数传递给 FTP 宏