如何将变量传递给curl

时间:2013-05-15 23:30:45

标签: bash shell curl

关于将变量放入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时,它可以正常工作。

如何才能使其发挥作用?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

另一种(类似的)方式。还建议您引用 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")"
相关问题