Bash中的cURL - 在单引号之间传递变量

Oph*_*paz 1 bash shell curl

我试图通过命令行将参数传递给cURL,这样:

curl -s -X POST -H "Content-Type: text/xml" -H "Cache-Control: no-cache" -d '<Data Token="someToken" Name='"$appName"' ID='"$someVar"' ParseAppID='"$someVar"' ParseRESTKey='"$someVar"' AndroidPackage='"$someVar"' Version="1"></Data>' 'https://prefix.something.com/somePath?InputType=Xml'
Run Code Online (Sandbox Code Playgroud)

(此行实际上是从Postman应用程序中提取的).

我用Google搜索了这个问题,发现了许多对我不起作用的解决方案(链接是过去的问题......):

  1. 我尝试通过结束单引号来隔离变量,这样:'before...'"${someVar}"'...after...'.无法完成请求.
  2. 我尝试使用文件传递变量(-d @fileName).无法发布.
  3. 我尝试<Data>双引号替换令牌周围的单引号 - 但命令显然不能接受这样的替换.

我得到的错误是<Error></Error>或者The server encountered an error and could not complete your request.

有没有机会存在其他解决方案?以前有人遇到过这样的问题吗?

我会很乐意提供任何帮助.

che*_*ner 5

您没有提供ID类似于您的价值的报价Name.也就是说,你需要

'<Data Token="someToken" Name="'"$appName"'" ...>'
                              ^^^
                              |||
                              ||+- shell quote to protect $appName
                              |+- shell quote enclosing the XML
                              +- literal quote embedded in the XML
Run Code Online (Sandbox Code Playgroud)

这导致字符串(假设appName=foo)

<Data Token="someToken" Name="foo" ...>
Run Code Online (Sandbox Code Playgroud)

  • @OphirHarpaz,如果你想知道你的更改是否正确,请使用`bash -x yourscript`来确切地看到传递给curl的内容(虽然这是shell转义的,而不是逐字节的).也就是说,一目了然,你在那里做的事情对我来说看起来很好 - 也就是说它应该代替有问题的变量; 结果是否是有效的文件是一个不同的讨论. (2认同)