2

How to make the command inside this for loop execute?

#!/bin/bash

for i in {8..12}
do
    printf "curl \"http://myurl?hour=20140131%02s\" -o file%02s.txt\n" "$i" "$i"
done

the current version of my script prints out the following lines:

curl "http://myurl?hour=2014013108" -o file08.txt
curl "http://myurl?hour=2014013109" -o file09.txt
curl "http://myurl?hour=2014013110" -o file10.txt
curl "http://myurl?hour=2014013111" -o file11.txt
curl "http://myurl?hour=2014013112" -o file12.txt

I'd like to change the script so that each line is executed and a file is saved at each curl request.

2
  • Just remove printf and the double-quotes. Commented Feb 4, 2014 at 17:23
  • Not sure I understand, which double quotes? all of them? If I remove all but the escaped ones it doesn't work. Commented Feb 4, 2014 at 17:31

4 Answers 4

3

No need to use eval, you can make it simple:

for i in {8..12}; do
    printf -v n %02d $i
    curl -s "http://myurl/?hour=20140131${n}" -o "file${n}.txt"
done
Sign up to request clarification or add additional context in comments.

4 Comments

The builtin printf allows you to: printf -v n %02d $i. That's faster since it does not have to spawn a subshell, but suffers in readability.
Thanks @glennjackman: I often forget that -v var option in printf
@chepnerL That worked for me on GNU bash, version 3.2.48(1)-release
There I go again, forgetting which version of bash adds various non-POSIX extensions :)
1

If you are using bash 4, there's no need for printf:

for i in {08..12}
do
    curl "http://myurl?hour=20140131$i" -o "file$i.txt"
done

Comments

1

Try to evaluate the generated command:

#!/bin/bash

for i in {8..12}
do
    eval curl $(printf "'http://myurl?hour=20140131%.2i' -o file%.2i.txt" "$i" "$i")
done

Also you can use the simplified code:

for i in $(seq -f "%02g" 08 12)
do
    curl "http://myurl?hour=20140131${i}" -o file${i}.txt
done

1 Comment

I strongly recommend against this. While it would work, there are safer alternatives that don't involve eval.
0

just add another line without printf

#!/bin/bash

for i in {8..12}
do
   printf "curl \"http://myurl?hour=20140131%02s\" -o file%02s.txt\n" 
   x=$(printf "%02d" "$i")
   curl "http://myurl?hour=20140131$x" -o file$x.txt 
done

2 Comments

The point of the printf is to force a leading zero for single digit values of i.
@chepner ok, i made the changes , %02d adds zero and not "%02s"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.