Bash variable in 2 quotes
Andrew Mclaughlin
I want to send a request like this with curl:
curl some parameters and headers --data-binary '{"secret":"$1"}'but $1 is not being variable. I tried using echo with this command:
echo '{"asd":"$1"}' dhkdgband I got this output:
{"asd":"$1"} dhkdgbHowever, I want to get this output:
{"asd":"dhkdgb"}And at curl request, I want to send this:
curl some parameters and headers --data-binary '{"secret":"argv 0 of script"}'How can I solve this issue?
32 Answers
There are several ways to do it ex. given
$ set -- 'foo bar'(to assign value foo bar to the shell's first positional parameter, as if in a script invoked like myscript "foo bar") then for example
$ echo '{"asd:":"'"$1"'"}'
{"asd:":"foo bar"}or
$ echo {\"asd:\":\""$1"\"}
{"asd:":"foo bar"}However you may find it cleaner to use the shell's printf builtin to create a formatted string that you can assign to a new variable:
$ printf -v data '{"asd": "%s"}' "$1"
$ echo "$data"
{"asd": "foo bar"}which you can then use as
curl some parameters and headers --data-binary "$data"Alternatively, since you appear to be trying to pass a JSON object to the curl command, you could consider using jq in place of printf:
$ jq -nc --arg x "$1" '{asd: $x}'
{"asd":"foo bar"}or similarly using the built-in $ARGS array
$ jq -nc --arg asd "$1" '$ARGS.named'
{"asd":"foo bar"}if you want to pass both the name and value to the constructor.
4I tend to use a heredoc and -d@- (read input data from stdin) for composing JSON request bodies:
cat <<EOF |
{ "secret": "$SECRET"
}
EOF
curl ... \ -X POST \ -H "Content-Type: application/json" \ "${BASE_URL%%/}/the/path" -d@-Yes, the syntax is a little weird.