Search code examples
bashquotesdouble-quotessingle-quotesmattermost

How can I execute a command which has a combination of quotes and double quotes?


The purpose of my script is to send a message to a Mattermost server. So I use curl to do so :

#!/bin/bash
message="This is my message with potentially several quotes in it ..."
url=http://www.myMatterMostServer.com/hooks/myMattermostKey
payload="{ \"text\" : \"$message\" }"
curlCommand="curl --insecure --silent --show-error --header 'Content-Type: application/json' -X POST --data '"$payload"' "$url
echo -e $curlCommand
$curlCommand

The echo command shows something which is executable if I copy it and execute it directly in a terminal.

But the last line doesn't execute correctly and I have this in the console :

++ curl --insecure --silent --show-error --header ''\''Content-Type:' 'application/json'\''' -X POST --data ''\''{' '"text"' : '"This' is my message with potentially several quotes in it '..."' '}'\''' http://poclo7.sii24.pole-emploi.intra/hooks/iht8rz8uwf81fgoq9ser8tda3y
curl: (6) Couldn't resolve host 'application'
curl: (6) Couldn't resolve host '"text"'
curl: (6) Couldn't resolve host ':'
curl: (6) Couldn't resolve host '"This'
curl: (6) Couldn't resolve host 'is'
curl: (6) Couldn't resolve host 'my'
curl: (6) Couldn't resolve host 'message'
curl: (6) Couldn't resolve host 'with'
curl: (6) Couldn't resolve host 'potentially'
curl: (6) Couldn't resolve host 'several'
curl: (6) Couldn't resolve host 'quotes'
curl: (6) Couldn't resolve host 'in'
curl: (6) Couldn't resolve host 'it'
curl: (6) Couldn't resolve host '..."'

I tried so much combinations of quotes, double quotes and $(command) ... Please help me :-)


Solution

  • Variables are for data, not code. See Bash FAQ 50. Define a function instead.

    curlCommand () {
        message=$1
        url=$2
        payload='{"text": "$message"}'
        curl --insecure --silent --show-error \
             --header 'Content-Type: application/json' \
             -X POST --data "$payload" "$url"
    }
    
    curlCommand "This is my message with potentially several quotes in it ..." http://www.myMatterMostServer.com/hooks/myMattermostKey
    

    Consider using jq to generate the payload to ensure that the contents of $message are properly escaped.

    payload=$(jq --arg msg "$message" '{text: $msg}')
    

    or pipe the output of jq directly to curl:

    jq --arg msg "$message" '{text: $msg}' | curl ... --data @- ...