ByteNirvana
ByteNirvana

Reputation: 5700

String interpolation in Bash

My code

#!/bin/bash
for (( c=0; c<=1127; c++ ))
do
id = 9694 + c
if (id < 10000); then
    wget http://myurl.de/source/image/08_05_27_0${id}.jpg
else 
    wget http://myurl.de/source/image/08_05_27_${id}.jpg
fi
done 

I only get

./get.sh: line 5: 10000: No such file or directory
--2009-05-06 11:20:36--  http://myurl.de/source/image/08_05_27_.jpg

without the number.

The corrected code:

#!/bin/bash
for (( c=0; c<=1127; c++ ))
do
id=$((9694+c))
if (id -lt 10000); then
    wget http://myurl.de/source/image/08_05_27_0${id}.jpg
else 
    wget http://myurl.de/source/image/08_05_27_${id}.jpg
fi
done 

And even better:

for i in $(seq 9694 10821) ; do
    _U=`printf "http://myurl.de/source/image/08_05_27_%05d.jpg" $i`
    wget $_U 
done

Upvotes: 16

Views: 17266

Answers (4)

greg
greg

Reputation: 685

I'll opt for simpler solution

for i in $(seq 9694 10821) ; do
    _U=`printf "http://myurl.de/source/image/08_05_27_%05d.jpg" $i`
    wget $_U 
done

Upvotes: 17

Ville Laurikari
Ville Laurikari

Reputation: 29248

You are making a couple of mistakes with bash syntax, especially when dealing with arithmetic expressions.

  • You cannot put a space around the = sign when assigning to a variable.
  • In the assignment to "id", to invoke arithmetic evaluation, you need to use the $(( expression )) syntax.
  • For the "if" condition, you need double parentheses just like you're using with "for".

This should work:

#!/bin/bash
for (( c=0; c<=1127; c++ )); do
  id=$((9694 + c))
  if ((id < 10000)); then
    wget http://myurl.de/source/image/08_05_27_0${id}.jpg
  else
    wget http://myurl.de/source/image/08_05_27_${id}.jpg
  fi
done

Upvotes: 11

paxdiablo
paxdiablo

Reputation: 881293

This is what you need.

#!/bin/bash
for (( c=0; c<=1127; c++ ))
do
    ((id = 9694 + c))
    if [[ id -lt 10000 ]] ; then
        wget http://myurl.de/source/image/08_05_27_0${id}.jpg
    else 
        wget http://myurl.de/source/image/08_05_27_${id}.jpg
    fi
done

Upvotes: 3

joeytwiddle
joeytwiddle

Reputation: 31255

You need:

id=$((9694+c))
...
if [[ id < 10000 ]]; then

Upvotes: 1

Related Questions