1

I have an argument to a bash script which could be a string with spaces. How can I use this within a string concatenation such as below:

#!/usr/bin/env bash

curl -X POST -H 'Content-type: application/json' \
--data '{"text":"'$1'"}' https://hooks.slack.com/services/<rest of URL secret!>

From cmd line if I do:

$./myscript.sh oneword

It works perfectly fine. But if I pass a string with spaces:

$./myscript.sh "two words"

curl: (3) [globbing] unmatched close brace/bracket in column 5
invalid_payload%  

I have tried all sorts of quoting to concatenate it correctly, but to no avail. Thanks

1
  • Don't generate JSON by hand, unless (maybe) you already know that $1 is a valid JSON string. Commented Nov 4, 2019 at 15:47

1 Answer 1

1

You need to quote $1 as well in your JSON payload:

curl -X POST -H 'Content-type: application/json' \
--data '{"text":"'"$1"'"}' https://hooks.slack.com/services/<rest of URL secret!>
Sign up to request clarification or add additional context in comments.

3 Comments

Even this may fail if $1 can't safely be merged (it might contain a double quote itself).
If double quotes can also be passed in $1 then OP may use: "${1//\"/\\\"}"
Letting something like jq construct the JSON is far safer. "$(jq -n --arg x "$1" '{text: $x}')".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.