首页 > 解决方案 > 将变量插入 json 有效负载(松弛 webhook)问题的 Bash 脚本

问题描述

我正在尝试将一个变量插入到我的 json 有效负载中(在 shell 脚本中工作),但我不确定如何正确转义字符

我尝试了许多不同的转义方法,但我完全是个菜鸟,我要么返回文字字符串,要么它不运行

SLACK_ALERT_WEBHOOK=desiredurl

curl -X POST -H 'Content-type: application/json' --data '{"text": "*Daily Webhook Verification*", "attachments": [
        {
            "blocks": [
                {
                    "type": "section",
                    "text": {
                        "type": "mrkdwn",
                        "text": "Slack post failed for webhook, please investigate: $SLACK_ALERT_WEBHOOK"
                    }
                }
            ]
        }
    ]}' "$SLACK_ALERT_WEBHOOK"

我只想将 SLACK_ALERT_WEBHOOK 的值插入代码“文本”的这部分:“Slack post failed for webhook,请调查:$SLACK_ALERT_WEBHOOK 但它要么不运行,要么返回文字字符串。我有底部“$ SLACK_ALERT_WEBHOOK”在底部成功发送到我想要的松弛通道,所以我不担心。

多亏了tripleee,我才能正常工作:

curl -X POST -H 'Content-type: application/json' --data "{\"text\": \"*Verification*\", \"attachments\": [{\"blocks\": [{\"type\": \"section\",\"text\": {\"type\": \"mrkdwn\",\"text\": \"$SLACK_ALERT_WEBHOOK\"}}]}]}" $SLACK_ALERT_WEBHOOK

标签: jsonbashvariables

解决方案


尝试这个:

SLACK_ALERT_WEBHOOK=desiredurl

$(curl -X POST -H 'Content-type: application/json' --data '{"text": "*Daily Webhook Verification*", "attachments": [
        {
            "blocks": [
                {
                    "type": "section",
                    "text": {
                        "type": "mrkdwn",
                        "text": "Slack post failed for webhook, please investigate: `echo $SLACK_ALERT_WEBHOOK`"
                    }
                }
            ]
        }
    ]}' "`echo $SLACK_ALERT_WEBHOOK`")

使用echo <<variable>>它应该只是将其作为命令运行。我在自己的服务器上对其进行了测试,但在您的服务器上可能会有所不同。希望能帮助到你。


推荐阅读