shell 带有cURL的Bash循环[重复]

zengzsys  于 2023-01-17  发布在  Shell
关注(0)|答案(3)|浏览(175)
    • 此问题在此处已有答案**:

How can I use a variable in curl call within bash script [duplicate](2个答案)
Difference between single and double quotes in Bash(7个答案)
昨天关门了。
我尝试编写一个bash循环来使用cURL检索一系列数字,但我不太理解如何实现。下面的代码是我尝试检索pi的前100万位的示例,其中API一次只能接受1000位。

for i in {0..1000000..1000}
    do
    curl 'https://api.pi.delivery/v1/pi?start=$i&numberOfDigits=1000'
    echo $i
    done

另外,我想把返回值写入一个名为pi.txt的文件中,而不是在终端中显示它们。我应该在终端中还是在脚本中使用〉〉pi.txt命令?有人能帮我更正这个bash脚本吗?

byqmnocz

byqmnocz1#

在curl命令中使用双引号而不是单引号将URL括起来(单引号不允许您在那里扩展变量)

y0u0uwnf

y0u0uwnf2#

curl -o pi.txt "https://api.pi.delivery/v1/pi?start=${i}&numberOfDigits=1000"

应该可以。如果不行,可以试着去掉变量上的方括号。

xdnvmnnf

xdnvmnnf3#

API返回JSON,因此通常应该使用jq来获取内容。
就像

for ((i=0; i<1000000; i+=1000)); do
  printf "%s" \
    $(curl -s "https://api.pi.delivery/v1/pi?start=$i&numberOfDigits=1000" |
      jq '.content')
done | tr -d '"'

但是,在本例中,您是在循环中调用curl命令,应该避免在while循环中调用其他程序(jq)。

for ((i=0; i<1000000; i+=1000)); do
  curl -s "https://api.pi.delivery/v1/pi?start=$i&numberOfDigits=1000"
done | tr -cd '[0-9]'

重定向到脚本中的文件或使用命令行都可以,这正是你最喜欢的。当你想看到数字通过并重定向时,在末尾使用| tee pi.txt

相关问题