用于从命令行创建新github repos的bash脚本可以正常工作,除非给出多字描述:
REPOSTRING={\"name\":\"$1\",\"description\":\"$2\",\"license_template\":\"mit\"}
echo $REPOSTRING
curl https://api.github.com/user/repos?access_token=xxx -d $REPOSTRING
调用脚本script testrepo testdescription
按预期工作,但出现script testrepo "description with spaces"
错误:
{
"message": "Problems parsing JSON",
"documentation_url": "https://developer.github.com/v3"
}
curl: (6) Could not resolve host: with
curl: (3) [globbing] unmatched close brace/bracket in column 33
即使脚本中的REPOSTRING
显示为echo
REPOSTRING
{"name":"testrepo","description":"description with spaces","license_template":"mit"}
空格出现在双引号内。
我需要对$2
作业中的REPOSTRING
做些什么特别的事情吗?我试过这个
REPOSTRING={\"name\":\"$1\",\"description\":\""$2"\",\"license_template\":\"mit\"}
但引用$2
明确没有引起任何变化。
答案 0 :(得分:2)
如果您希望保证JSON解析器可以接受输出,请使用知道如何生成JSON的工具 - 例如jq:
repo_string=$(jq --arg name "$1" \
--arg description "$2" \
'.name=$name | .description=$description' \
<<<'{"license_template": "mit"}')
其他方法可能会遇到以下问题:
"
个字符(需要转义才能被视为数据而不是语法答案 1 :(得分:-1)
你必须引用字符串赋值:
REPOSTRING="{\"name\":\"$1\",\"description\":\"$2\",\"license_template\":\"mit\"}"