Bash
在 shell 腳本中的 json 有效負載中傳遞變數
在下面的場景中,傳入
${MY_ENV_VAR}
payload的方式是什麼?我將不得不逃脫:
a) 有效載荷的單引號
text
b) 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}"