Home > Back-end >  Bash Loop with cURL
Bash Loop with cURL

Time:01-16

I am trying to write a bash loop to retrieve a series of numbers using cURL, but I am having trouble understanding how to do it. The code below is an example of how I am trying to retrieve the first million digits of pi, where the API can only accept 1000 digits at a time.

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

Additionally, I would like to write the returned values to a file called pi.txt instead of displaying them in the terminal. Should I use the >>pi.txt command in the terminal or within the script? Can someone help me correct this bash script?

CodePudding user response:

Use double quotes instead of single quotes around your URL in the curl command (single quotes won't allow for the variable expansion you want there)

CodePudding user response:

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

should work. If not, maybe try removing the square brackets on the variable.

CodePudding user response:

The api returns JSON, so normally you should use jq to get the content.
Something like

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 '"'

However, in this case you are calling the curl command in a loop, and you should avoid calling additional programs (jq) in a while loop.

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]'

Redirecting to a file in the script or using the commandline are both possible, just what you like best. When you want to see the digits coming through and redirect, use | tee pi.txt at the end.

  • Related