2

我目前有这个脚本...

#!/bin/bash
# Check NGINX
nginxstat=$(service nginx status)

# Checking Sites
hostsite="localhost:81 - "$(curl --silent --head --location --output /dev/null --write-out '%{http_code}'  http://localhost:81 | grep '^2')

##########
# Send to Slack
curl -X POST --data '{"channel":"#achannel","username":"Ansible", "attachments": [{"fallback":"NGINX Reload","pretext":"'"$HOSTNAME"'","color":"good","fields":[{"title":"nginx localhost","value":"'"$hostsite"'","short":true},{"title":"NGINX","value":"'"$nginxstat"'","short":true}]}]}' -i https://xxx.slack.com/services/hooks/incoming-webhook?token=xxx

我已经尝试了又失败了;我想获取 nginx 配置测试的结果并将其推入。在运行此之前,nginx 重新加载开始,重新加载会自行进行配置检查,因此如果配置错误,服务器会保持运行状态。所以我的 nginx 状态命令(有效)显示

NGINX
----------------
nginx (pid  1234) is running...

但是我无法在配置测试中得到相同的结果,我希望这是由于所需转义的性质以及它抽出的其他垃圾

nginx: [warn] "ssl_stapling" ignored, issuer certificate not found
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
4

1 回答 1

3

在将变量嵌入 POST 数据之前,使用jq将变量转换为 JSON 字符串:

$ echo '"some quoted stuff"' | jq @json
"\"some quoted stuff\""

例如:

nginxstat=$(service nginx status | jq @json)

然后嵌入不带引号的。另请参阅手册

或者,如果您希望它转义 JSON,则 bash 转义:

echo '"some quoted stuff"' | jq "@json | @sh"
"'\"some quoted stuff\"'"

我有没有提到jq是我最喜欢的东西?

http://stedolan.github.io/jq/

于 2014-10-15T16:27:04.850 回答