Bash for循环功能

时间:2014-02-04 17:17:43

标签: bash curl

如何在for循环中执行命令执行?

#!/bin/bash

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

我的脚本的当前版本打印出以下行:

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

我想更改脚本,以便执行每一行并在每个curl请求中保存一个文件。

4 个答案:

答案 0 :(得分:3)

无需使用eval,您可以简化:

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

答案 1 :(得分:1)

尝试评估生成的命令:

#!/bin/bash

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

您也可以使用简化代码:

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

答案 2 :(得分:1)

如果您使用bash 4,则无需printf

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

答案 3 :(得分:0)

只需添加另一行不带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