Shell脚本使用curl循环遍历URL

时间:2013-04-21 12:53:56

标签: bash loops curl

我一直在尝试创建一个简单的脚本,它将从.txt文件中获取查询列表,附加主url变量,然后抓取内容并将其输出到文本文件。

这是我到目前为止所拥有的:

#!/bin/bash

url="example.com/?q="
for i in $(cat query.txt); do
    content=$(curl -o $url $i)
    echo $url $i
    echo $content >> output.txt
done

列表:

images
news
stuff
other

错误日志:

curl: (6) Could not resolve host: other; nodename nor servname provided, or not known
example.com/?q= other

如果我直接从命令行使用此命令,我会在文件中输出一些内容:

curl -L http://example.com/?q=other >> output.txt

最终我希望输出为:

fetched:    http://example.com/?q=other
content:    the output of the page

followed by the next query in the list.

2 个答案:

答案 0 :(得分:25)

使用更多报价!<​​/ p>

请改为尝试:

url="example.com/?q="
for i in $(cat query.txt); do
    content="$(curl -s "$url/$i")"
    echo "$content" >> output.txt
done

答案 1 :(得分:4)

您已嵌套引号,请尝试以下操作:

#!/bin/bash

url=https://www.google.fr/?q=
while read query
do
    content=$(curl "{$url}${query}")
    echo $query
    echo $content >> output.txt
done < query.txt