在 shell 脚本中传递 json 负载中的变量

在 shell 脚本中传递 json 负载中的变量

${MY_ENV_VAR}在下面的场景中, payload的传入方式是什么?

我将不得不逃脱:

a) 负载的单引号

textb) json字段值的双引号

${MY_ENV_VAR)当然我需要进行插值。

#!/bin/bash

COMMAND=${MY_ENV_VAR}    

curl -X POST --data-urlencode 'payload={"channel": "#alerts", "username": "k8s-cronjobs-bot", "text": "Command ${MY_ENV_VAR} run with success", "icon_emoji": ":ghost:"}' ${SLACK_WEBHOOK}

答案1

jq

$ payload='{"channel": "#alerts", "username": "k8s-cronjobs-bot", "text": "", "icon_emoji": ":ghost:"}'
$ MY_ENV_VAR='"foo"'
$ echo "$payload" | jq --arg cmd "$MY_ENV_VAR" '.text = "Command " + $cmd + " run with success"'
{
  "channel": "#alerts",
  "username": "k8s-cronjobs-bot",
  "text": "Command \"foo\" run with success",
  "icon_emoji": ":ghost:"
}

所以你的脚本看起来像:

#!/bin/bash

COMMAND=${MY_ENV_VAR}    
payload='{"channel": "#alerts", "username": "k8s-cronjobs-bot", "text": "", "icon_emoji": ":ghost:"}'
payload=$(echo "$payload" | jq -r --arg cmd "$COMMAND" '.text = "Command " + $cmd + " run with success"')
curl -X POST --data-urlencode "payload=$payload"  "${SLACK_WEBHOOK}"

答案2

或者,用于printf帮助混合引号:

printf -v payload '{"channel": "#alerts", "username": "k8s-cronjobs-bot", "text": "Command %s run with success", "icon_emoji": ":ghost:"}' "$MY_ENV_VAR"
curl -X POST --data-urlencode "payload=$payload" "$SLACK_WEBHOOK"

相关内容