18

How can I write a bash script that is going to do the following:

URL = "example.com/imageID="
while (1..100)
   wget URL + $i #it will wget example.com/imageID=1, then 2, then 3, etc
done

So I have a number of loops to perform, a URL which is ended with a number from the loop. I need to wget all of these.

0

5 Answers 5

43

if you are using Bash 4.0, you can do this:

wget example.com/imageId={1..100}.jpg
15

It's fairly easy, even for someone with not much programming experience. When in doubt always read the Bash manual:

for i in {1..100}
do
    wget "example.com/imageID=$i"
done
3
  • As a matter of principle, you should enclose the $i in quotes: wget "example.com/imageID=$i" Sep 24, 2018 at 5:22
  • this probably works great. however, i start from "00008000" and the wget shoots errors because for some reasn it skips the first four zeroes.
    – esaruoho
    Dec 10, 2019 at 5:47
  • @esaruoho that's because "00008000" parses as the number 8000 - i'd solve that with either padding/number formatting (do all your "numbers" have eight characters?) or, if they all start with 0000, start from 8 and add the extra zeroes into the quoted string "example.com/imageID=0000$i"
    – Sandra
    Nov 24, 2023 at 11:29
1

In case variable is not at end of URL and variable is between underscores:
example.com/imageID_1_2018.gif
example.com/imageID_2_2018.gif
example.com/imageID_3_2018.gif
.
.
.
example.com/imageID_100_2018.gif

wget example.com/imageID_{1..100}_2018.gif
equivalently:
for ((i=1;i<=100;i++)); do wget example.com/imageID_${i}_2018.gif; done

2
  • 3
    Welcome to Super User. Please edit your answer to provide more detail. Not everyone reading your post may understand how it answers the OP's question without a more detailed explanation. Sep 23, 2018 at 20:49
  • 1
    I’m not sure this is an answer.  It looks like an explanation of the accepted answer (and not a very clear one). Sep 24, 2018 at 0:21
1

The accepted answer is great. I used something similar to download in parallel which may be useful:

echo example.com/imageId={1..100}.jpg | xargs -n 1 -P 10 wget
0

This will also automatically add the leading zeros if necessary:

wget example.com/imageID_{001..100}_2018.gif

like

example.com/imageID_001_2018.gif

instead of

example.com/imageID_1_2018.gif

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .