如何执行具有引号和双引号组合的命令?

时间:2017-05-31 08:03:17

标签: bash quotes double-quotes single-quotes mattermost

我的脚本的目的是向Mattermost服务器发送消息。 所以我使用curl来做到这一点:

#!/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

如果我复制并直接在终端中执行它,echo命令会显示可执行的内容。

但是最后一行没有正确执行,我在控制台中有这个:

++ 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 '..."'

我尝试了很多引号,双引号和$(命令)的组合......请帮助我: - )

1 个答案:

答案 0 :(得分:1)

变量用于数据,而不是代码。见Bash FAQ 50。改为定义一个函数。

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

考虑使用jq生成有效负载,以确保$message的内容得到正确转义。

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

或将jq的输出直接传递给curl

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