【问题标题】:How to pass dynamic parameters in curl requestcurl请求中如何传递动态参数
【发布时间】:2017-08-05 10:06:58
【问题描述】:

我正在将动态值传递给测试方法并执行 curl 请求。 $PARAMETERS 有问题。

当我执行以下方法时,我得到如下错误

错误:-

curl: option -F: requires parameter
curl: try 'curl --help' or 'curl --manual' for more information

功能:-

testing() {

local URL=$1
local HTTP_TYPE=$2
local PARAMETERS=$3

# store the whole response with the status at the and
HTTP_RESPONSE=$(curl -w "HTTPSTATUS:%{http_code}" -X $HTTP_TYPE $URL $PARAMETERS)

echo $HTTP_RESPONSE
}

URL='https://google.com'
HTTP_TYPE='POST'
PARAMETERS="-F 'name=test' -F 'query=testing'"


result=$(testing $URL $HTTP_TYPE $PARAMETERS)

仅供参考,上面是一个示例方法,并且正在使用 shell 脚本。请告诉我如何解决这个问题?

【问题讨论】:

    标签: shell curl post


    【解决方案1】:

    由于您在第三个参数中传递了多个命令参数,因此当您在函数中使用不带引号的变量时,shell 会进行拆分。

    你最好使用shell数组来存储PARAMETERS参数。

    你的功能是:

    testing() {
       local url="$1"
       local httpType="$2"
    
       shift 2 # shift 2 times to discard first 2 arguments
       local params="$@" # store rest of them in a var
    
       response=$(curl -s -w "HTTPSTATUS:%{http_code}" -X "$httpType" "$url" "$params")
       echo "$response"
    }
    

    并将其称为:

    url='https://google.com'
    httpType='POST'
    
    params=(-F 'name=test' -F 'query=testing')
    result=$(testing "$url" "$httpType" "${params[@]}")
    

    此外,您应该避免在 shell 脚本中使用全大写变量名,以避免与环境变量发生冲突。


    如果你没有使用bash,你也可以使用:

    params="-F 'name=test' -F 'query=testing'"
    result=$(testing "$url" "$httpType" "$params")
    

    Code Demo

    【讨论】:

    • 我收到“语法错误:”(“意外”在这一行 - PARAMETERS=(-F 'name=test' -F 'query=testing')
    • 我只对我的所有脚本文件使用 shell 脚本。我无法更改为 bash。它会影响我的整个脚本。
    • 检查已编辑的答案,尽管将 sh 更改为 bash 通常不会破坏任何内容。
    • 我得到 sample.sh: 421: local: -F: bad variable name sample.sh: 421: sample.sh: 'name: bad variable name in this line local params=$3跨度>
    • 但我的回答中没有local params=$3。您还需要从答案中复制/粘贴我建议的功能代码。
    猜你喜欢
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多