【问题标题】:How to pass variable into curl如何将变量传递给curl
【发布时间】:2013-05-15 23:30:44
【问题描述】:

关于将变量放入url中的curl命令还有其他问题。

我想在脚本顶部定义一个变量来交换值,如下所示:

# MODE=-v
MODE='-sS -w "\nEffective URL: %{url_effective} \nSize: %{size_download} \nTotal time: %{time_total} \nRedirect URL: %{redirect_url}"'

并在几个 curl 请求中使用它,如下所示:

PAGE=$(curl $MODE --include --location --config curl.config $TARGET1) 

不幸的是,我尝试过的引用($MODE 或 $TARGET1)或${MODE} 的任何变体都不会导致 -w 选项被接受并出现在 $PAGE 的底部。将$MODE 替换为长版本时效果很好。

如何让它发挥作用?

【问题讨论】:

    标签: bash shell curl


    【解决方案1】:

    另一种(类似的)方式。还建议您引用 URI 之类的变量。 第二点是要注意大写变量名。因为它们很容易因环境变量等而崩溃。

    #!/bin/bash
    
    url="$1"
    
    w=("-sS"
    "-w
    Effective URL: %{url_effective}
    Size         : %{size_download}
    Total time   : %{time_total}
    Redirect URL : %{redirect_url}"
    )
    
    page="$(curl "${w[@]}" --include --location --config curl.config "$url")"
    

    【讨论】:

    • 感谢您提供有关 uc 名称的评论。这个解决方案似乎更接近问题。
    【解决方案2】:

    一种方法

    w=(
      '\nEffective URL: %{url_effective}'
      '\nSize: %{size_download}'
      '\nTotal time: %{time_total}'
      '\nRedirect URL: %{redirect_url}'
    )
    curl -Ss --include --location --config curl.config -w "${w[*]}" icanhazip.com
    

    当您按照自己的方式进行操作时,会发生分词,因此 -w 字符串会在每个空格上拆分,而不是作为单个字符串传递。

    $ set -x
    
    $ : curl $MODE --include --location --config curl.config icanhazip.com
    + : curl -sS -w '"\nEffective' URL: '%{url_effective}' '\nSize:' '%{size_download}' '\nTotal' time: '%{time_total}' '\nRedirect' URL: '%{redirect_url}"' --include --location --config curl.config icanhazip.com
    

    【讨论】:

    • 不错。你知道为什么 MODE 变量不能正确扩展吗?
    • 史蒂文,我不明白你编辑的代码和第二个代码块。 $ set -x 在做什么?第二,第2行是什么?这看起来像我原来的......
    猜你喜欢
    • 1970-01-01
    • 2017-07-15
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 2018-12-28
    • 2011-04-12
    相关资源
    最近更新 更多