Bash

在 shell 腳本中的 json 有效負載中傳遞變數

  • June 26, 2019

在下面的場景中,傳入${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}

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}"

引用自:https://unix.stackexchange.com/questions/527013