【问题标题】:Redirect curl to while loop将 curl 重定向到 while 循环
【发布时间】:2015-05-16 06:42:33
【问题描述】:

有没有办法将 curl 输出重定向到 while 循环?

while read l; do 
  echo 123 $l; 
done < curl 'URL'

或者有更好的方法吗?我只需要读取页面的内容并在每一行添加一些内容并将其保存到文件中。

【问题讨论】:

    标签: linux bash curl


    【解决方案1】:

    您将希望使用 进程替换 重定向 curl 的输出,如下所示:

    while read -r l; do 
        echo "123 $l"
    done < <(curl 'URL')
    

    您还可以使用带引号的命令替换herestring的输出,如下所示:

    while read -r l; do 
        echo "123 $l"
    done <<<"$(curl 'URL')"
    

    (虽然进程替换是首选)

    注意:对于重定向到文件,您可以重定向块的输出,而不是一次重定向一行:

    :>outfile    ## truncate outfile if it exists
    {
        while read -r l; do 
            echo "123 $l"
        done < <(curl 'URL') 
    }>outfile
    

    【讨论】:

    • 非常好。 -r 是为了防止某种注入攻击吗?
    【解决方案2】:

    你可以使用管道运算符|

    curl 'URL' | while read l; do 
       echo 123 $l >> file.txt
    done
    

    【讨论】:

    • 您不需要 管道,事实上,您应该避免使用管道来提供读取循环。使用进程替换。
    • @DavidC.Rankin 我愿意接受我错了,但如果你能说出为什么,即为什么你不应该使用管道来提供读取循环,那就太好了。
    • 我没有说你错,你可以使用pipe,但就像任何时候你认为cat file | ...一样,你刚刚提交了一个UUOC(不必要使用cat)。 重定向是从一个进程向另一个进程提供输入/输出的正确方法,除非你有两个以上。那么你必须使用管道。其次,每个管道都会生成一个额外的子shell,几乎在所有情况下都不需要。
    • 当你把它放在猫方面时是有道理的。谢谢。
    猜你喜欢
    • 2015-10-30
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多