【问题标题】:Pass variable as options to curl in shell script linux [duplicate]将变量作为选项传递给shell脚本linux中的curl [重复]
【发布时间】:2019-03-11 03:13:33
【问题描述】:

我正在尝试通过脚本使用 curl 更新网站的一些信息,但效果不佳,这是我拥有的代码:

CURL_STD_OPTS="-k --header 'Content-Type: application/json' --header 'Accept: application/json'
curl  "$CURL_STD_OPTS" -X POST --data '{ "actual": '"$BAL"' }' "'$websiteurl'"

这是输出消息:

jdelaoss@infcet99:/tools/saadmin/occtools_morning_checks $ ./test.sh
curl: option -k --header 'Content-Type: application/json' --header 'Accept: application/json': is unknown

如果我直接从 shell 运行脚本并使用它工作的选项。

【问题讨论】:

    标签: linux bash shell curl


    【解决方案1】:

    您需要使用数组,而不是常规变量。

    curl_std_opts=( -k --header 'Content-Type: application/json' --header 'Accept: application/json')
    curl "${curl_std_opts[@]}" -X POST --data "{\"actual\": $BAL}" "$websiteurl"
    

    为了安全起见,您应该使用jq 之类的工具来生成 JSON,而不是依靠参数插值来生成有效的 JSON。

    curl "${curl_std_opts[@]}" -X POST --data "(jq --argjson b "$BAL" '{actual: $b}') "$websiteurl"
    

    【讨论】:

    • 非常感谢,它现在对我有用。顺便说一句,我必须将数组中的数组元素拆分如下CURL_STD_OPTS=("-k" "--header" "Content-Type: application/json" "--header" "Accept: application/json"如果您想将其添加到答案中!
    • 这应该产生与答案完全相同的数组;未引用的字符串不包含任何需要引用的字符,并且单引号字符串中的任何内容在双引号内的行为都不会有所不同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 2015-09-09
    • 2013-11-02
    • 2014-03-11
    • 1970-01-01
    • 2023-04-03
    • 2012-06-03
    相关资源
    最近更新 更多