【问题标题】:Parsing variables in curl with bash script使用 bash 脚本解析 curl 中的变量
【发布时间】:2017-08-16 13:55:56
【问题描述】:

嘿,我正在使用管道 curl 方法从帖子创建任务。当我从带有硬编码值的终端运行时,它工作正常。但是当我尝试用变量执行它时,它会抛出一个错误:

脚本:

#!/bin/bash
echo "$1"
echo "$2"
echo "$3"
echo "$4"
echo "$5"
echo '{
  "transactions": [
    {
      "type": "title",
      "value": "$1"
    },
    {
      "type": "description",
      "value": "$2"
    },
    {
      "type": "status",
      "value": "$3"
    },
    {
      "type": "priority",
      "value": "$4"
    },
    {
       "type": "owner",
       "value": "$5"
    }
  ]
}' | arc call-conduit --conduit-uri https://mydomain.phacility.com/ --conduit-token mytoken maniphest.edit

执行:

./test.sh "test003 ticket from api post" "for testing" "open" "high" "ahsan"

输出:

test003 ticket from api post
for testing
open
high
ahsan
{"error":"ERR-CONDUIT-CORE","errorMessage":"ERR-CONDUIT-CORE: Validation errors:\n  - User \"$5\" is not a valid user.\n  - Task priority \"$4\" is not a valid task priority. Use a priority keyword to choose a task priority: unbreak, very, high, kinda, triage, normal, low, wish.","response":null}

正如您所看到的错误,它将 $4 和 $5 读取为值而不是变量。而且我无法理解如何在这些参数中使用 $variables 作为输入。

【问题讨论】:

    标签: json bash curl environment-variables echo


    【解决方案1】:

    您在最后一个 echo 周围使用单引号,以便您可以在 JSON 中使用双引号,但这会导致 echo 打印字符串而不扩展任何内容。您需要对字符串使用双引号,因此您必须转义其中的双引号。

    用这个替换最后一个echo

    echo "{
      \"transactions\": [
        {
          \"type\": \"title\",
          \"value\": \"$1\"
        },
        {
          \"type\": \"description\",
          \"value\": \"$2\"
        },
        {
          \"type\": \"status\",
          \"value\": \"$3\"
        },
        {
          \"type\": \"priority\",
          \"value\": \"$4\"
        },
        {
           \"type\": \"owner\",
           \"value\": \"$5\"
        }
      ]
    }"
    

    它会起作用的。为避免此类问题,您可以查看http://wiki.bash-hackers.orghttp://mywiki.wooledge.org/BashGuide 以获取针对bash 新手的一些一般提示。此外,您可以将shellcheck 与许多文本编辑器一起使用,它们会自动发现此类错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-04
      • 2017-04-12
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      • 2020-02-09
      相关资源
      最近更新 更多