我有一个我认为很简单的脚本:
#!/bin/sh
URL=myserver:9443
myCmd="curl -sS -k -X 'POST' 'https://"
myCmd+=$URL
myCmd+="/SKLM/rest/v1/ckms/accessToken' "
myCmd+="-H 'accept: application/json' "
myCmd+="-H 'Accept-Language: en' "
myCmd+="-H 'Content-Type: application/json' "
myCmd+="-d '{ \"userid\": \"SKLMAdmin\", \"password\": \"XXX\" }'"
echo $myCmd
authTok=$($myCmd)
当我运行它时,我得到这个:
curl -sS -k -X 'POST' 'https://myserver:9443/SKLM/rest/v1/ckms/accessToken' -H 'accept: application/json' -H 'Accept-Language: en' -H 'Content-Type: application/json' -d '{ "userid": "SKLMAdmin", "password": "XXX" }'
curl: (3) URL using bad/illegal format or missing URL
curl: (6) Could not resolve host: application
curl: (6) Could not resolve host: en'
curl: (6) Could not resolve host: application
curl: (3) URL using bad/illegal format or missing URL
curl: (6) Could not resolve host: "SKLMAdmin",
curl: (3) URL using bad/illegal format or missing URL
curl: (6) Could not resolve host: "XXX"
curl: (3) unmatched close brace/bracket in URL position 1:
}'
如果我将 echo 输出的内容剪切并粘贴到 shell 中,该命令可以正常工作,但是从脚本内执行它的行会给出该字符串错误。
我认为我违反了在脚本中使用 cURL 的一些基本规则,但我似乎无法弄清楚。我需要将 URL 设为变量(最终将用户名和密码设为变量),这似乎就是问题所在。
答案1
既然你已经用 bash 标记了你的问题,我假设你可以使用 bash。在这种情况下你应该使用 bash 因为它支持数组。数组是存储命令/命令参数的更好选择:
#!/usr/bin/env bash
url=myserver:9443
uri='/SKLM/rest/v1/ckms/accessToken'
#data='{ \"userid\": \"SKLMAdmin\", \"password\": \"XXX\" }'
data=$(jo userid=SKLMAdmin password=XXX)
opts=(
-sSk
-X POST
-H 'accept: application/json'
-H 'Accept-Language: en'
-H 'Content-Type: application/json'
-d "$data"
)
authtok=$(curl "${opts[@]}" "${url}${uri}")
该数组允许您单独扩展每个单独的选项,但就像单独引用它们一样,以防止分词和其他不需要的扩展。
"${opts[@]}"
将扩展到:
'-sSk' '-H' 'accept: application/json' '-H' 'Accept-Language: en' '-H' 'Content-Type: application/json' '-d' '{ \"userid\": \"SKLMAdmin\", \"password\": \"XXX\" }'