tackdetack
tackdetack

Reputation: 639

For While Do Loop bash

I've got the following loop that will print out Url.com/1.jpg to xx.jpg (for any number of my choosing in {1..2})

I need to run this loop for multiple URL's and not interested in adding a new for loop for each URL.

for i in {1..2}; do 
echo "'http://url.com/$i.jpg',"
echo "'http://url1.com/$i.jpg'"
done

When run as is, I get

'http://url.com/1.jpg',
'http://url1.com/1.jpg'
'http://url.com/2.jpg',
'http://url1.com/2.jpg'

What is the easiest way to make the text display as:

'http://url.com/1.jpg',
'http://url.com/2.jpg',
'http://url1.com/1.jpg'
'http://url1.com/2.jpg'

For, While Do? Nested loops?

Upvotes: 0

Views: 104

Answers (3)

dannysauer
dannysauer

Reputation: 3867

Replace done with done | sort at the end of your loop. Or stick your URLs in a second list, as in this example, since lists are typically expanded left to right:

$ echo {a,b}{1..3}
a1 a2 a3 b1 b2 b3

The second approach has the benefit of letting you do your wget or whatever in one command, like wget http://{base_url1,base_url2}/image{1..3}.jpg, and is a general structure I use at least weekly.

Upvotes: 0

chepner
chepner

Reputation: 530960

No (explicit) loops! :)

printf "'http://url.com/%d.jpg',\n" {1..2}
printf "'http://url1.com/%d.jpg'\n" {1..2}

Or, further generalize by adding one loop:

urls=(
    "'http://url.com/%d.jpg',"
    "'http://url1.com/%d.jpg'"
)
for url in "${urls[@]}"; do
    printf "$url\n" {1..2}
done

Upvotes: 2

WillShackleford
WillShackleford

Reputation: 7008

Just use two for loops.

for i in {1..2}; do 
echo "'http://url.com/$i.jpg',"
done
for i in {1..2}; do 
echo "'http://url1.com/$i.jpg'"
done

Upvotes: 0

Related Questions