如何在bash脚本中转义用curl发布的JSON变量?

时间:2015-06-03 15:21:46

标签: bash curl mandrill

我正在通过他们的API在bash脚本中向Mandrill提交消息,而'message'变量的内容导致API调用返回错误:

An error occured: {"status":"error","code":-1,"name":"ValidationError","message":"You must specify a key value"}

$ message_body变量的内容是:

Trigger: Network traffic high on 'server'
Trigger status: PROBLEM
Trigger severity: Average
Trigger URL:

Item values:

1. Network traffic inbound (server:net.if.in[eth0,bytes]): 3.54 MBytes
2. Network traffic outbound (server:net.if.out[eth0,bytes]): 77.26 KBytes
3. *UNKNOWN* (*UNKNOWN*:*UNKNOWN*): *UNKNOWN*

Original event ID: 84

我不确定该字符串的哪一部分会将其丢弃,但似乎有些事情导致JSON在提交给Mandrill的API时无效。

如果我将上述消息更改为简单的内容,例如“测试123”,则会成功提交消息。

执行POST的代码如下:

#!/bin/bash
...
message_body = `cat message.txt`
msg='{ "async": false, "key": "'$key'", "message": { "from_email": "'$from_email'", "from_name": "'$from_name'", "headers": { "Reply-To": "'$reply_to'" }, "auto_html": false, "return_path_domain": null, "subject": "'$2'", "text": "'$message_body'", "to": [ { "email": "'$1'", "type": "to" } ] } }'
results=$(curl -A 'Mandrill-Curl/1.0' -d "$msg" 'https://mandrillapp.com/api/1.0/messages/send.json' -s 2>&1);
echo "$results"

我该怎样做才能确保准备$message_body变量并准备好作为有效的JSON提交?

1 个答案:

答案 0 :(得分:4)

我怀疑问题是缺少引用变量

msg='{ "async": false, "key": "'$key'", "message": { "from_email": "'$from_email'", "from_name": "'$from_name'", "headers": { "Reply-To": "'$reply_to'" }, "auto_html": false, "return_path_domain": null, "subject": "'$2'", "text": "'$message_body'", "to": [ { "email": "'$1'", "type": "to" } ] } }'
# ..............................^^^^ no quotes around var ...........^^^^^^^^^^^...................^^^^^^^^^^...............................^^^^^^^^^...................................................................^^..............^^^^^^^^^^^^^.........................^^

请改为尝试:每个变量中的任何双引号都会被转义。

escape_quotes() { echo "${1//\"/\\\"}"; }
msg=$(
    printf '{ "async": false, "key": "%s", "message": { "from_email": "%s", "from_name": "%s", "headers": { "Reply-To": "%s" }, "auto_html": false, "return_path_domain": null, "subject": "%s", "text": "%s", "to": [ { "email": "%s", "type": "to" } ] } }' \
        "$(escape_quotes "$key")"          \
        "$(escape_quotes "$from_email")"   \
        "$(escape_quotes "$from_name")"    \
        "$(escape_quotes "$reply_to")"     \
        "$(escape_quotes "$2")"            \
        "$(escape_quotes "$message_body")" \
        "$(escape_quotes "$1")" 
)