Reputation: 3
A bash script for creating new github repos from the command line works unless given multi word descriptions:
REPOSTRING={\"name\":\"$1\",\"description\":\"$2\",\"license_template\":\"mit\"}
echo $REPOSTRING
curl https://api.github.com/user/repos?access_token=xxx -d $REPOSTRING
Calling the script script testrepo testdescription
works as expected, but script testrepo "description with spaces"
errors out with:
{
"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
It appears the spaces are breaking up the REPOSTRING
even though the echo
in the script shows REPOSTRING
as
{"name":"testrepo","description":"description with spaces","license_template":"mit"}
with the spaces appearing within double quotes.
Is there something special I need to do with the $2
in the REPOSTRING
assignment that I'm missing? I've attempted it as
REPOSTRING={\"name\":\"$1\",\"description\":\""$2"\",\"license_template\":\"mit\"}
but quoting $2
explicitly caused no change.
Upvotes: 0
Views: 226
Reputation: 296049
If you want to be guaranteed that output will be accepted by JSON parser, use a tool that knows how to generate JSON -- such as jq:
repo_string=$(jq --arg name "$1" \
--arg description "$2" \
'.name=$name | .description=$description' \
<<<'{"license_template": "mit"}')
Other approaches might have trouble with conditions including:
"
characters (which need to be escaped to be treated as data rather than syntaxUpvotes: 2
Reputation: 69426
You have to quote the string assignment:
REPOSTRING="{\"name\":\"$1\",\"description\":\"$2\",\"license_template\":\"mit\"}"
Upvotes: -1