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 Numbers in {0..100000000000000..1000}
do
curl "https://api.pi.delivery/v1/pi?start=$Numbers&numberOfDigits=100&radix=10"
echo $Numbers
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?
and another problem i'm encountering is that when i go higher in range values for example first billion instead of million i get a 'invalid request: start' how can this be solved
the code above works with 1000000 but not when you increase the value
CodePudding user response:
If I use {0..100000000000000..1000}
, I get:
bash: brace expansion: failed to allocate memory for 1215752193 elements
You can use
seq 0 1000 100000000000000 | while read Numbers
do
…
done
instead, but you'll need a lot of patience.
CodePudding user response:
Give this a try:
#!/bin/bash
file_path="path/to/pi.txt"
for i in {0..1000000..1000}
do
curl 'https://api.pi.delivery/v1/pi?start='"$i"'&numberOfDigits=1000'
echo "$i"
done > "$file_path"
When you use single quotes around a string, it preserves its literal value, the difference from double quotes is the exception for the character $
amongst others.
This post describes this matter more deeply, referring to the Bash manual.