如何将日期命令嵌入到json请求中

时间:2018-02-03 21:43:30

标签: bash

我试图通过GitHubs API创建私人仓库的夜间版本。我想通过bash提供的date命令将日期添加到每晚发布。但我不知道如何逃避命令。这就是我想要完成的。

curl -u "$1:$2" -XPOST \
  "https://api.github.com/repos/RazortoothRTC/ambra-nocigramweb-webhook/releases" \
  -H "Content-Type: application/json" \
  -d '{"tag_name":"ambra-nocigramweb-webhook-nightly",\
       "target_commitish":"master",\
       "name":"nightly-**$(date +%d-%m-%Y)**",\
       "body":"Nightly release of ambra-nocigramweb-webhook",\
       "draft":false,\
       "prerelease":false}'

它不明显,但我想在json post请求中嵌入$(date +%d-%m-%Y)

3 个答案:

答案 0 :(得分:1)

您可以使用jq安全地生成日期以及其余的JSON。

json=$(jq -n '{
   tag_name: "ambra-nocigramweb-webhook-nightly",
   target_commitish: "master",
   name: "nightly-\(now|gmtime|strftime("%d-%m-%Y"))",
   body: "Nightly release of ambra-nocigramweb-webhook",
   draft: false,
   prerelease: false
 }')

答案 1 :(得分:0)

由于您在$()内正在运行'...',因此它是scaleY。尝试这样的事情:

curl ... -d '{..., "name":"nightly-'$(date +%d-%m-%Y)'", ...}'

通过这样做,子shell调用$()的结果将在构建curl -d的参数字符串之前进行评估。

更易读的版本如下所示:

DATE=$(date +%d-%m-%Y)
curl ... -d '{..., "name":"nightly-'$DATE'", ...}'

答案 2 :(得分:0)

简单引用的使用阻止bash解释字符串。 双引号可以,但你需要在json里面。

所以你可以使用printf

printf '{"tag_name":"ambra-nocigramweb-webhook-nightly","target_commitish":"master","name":"nightly-**%s**","body":"Nightly release of ambra-nocigramweb-webhook","draft":false,"prerelease":false}' $(date +%d-%m-%Y)

{"tag_name":"ambra-nocigramweb-webhook-nightly","target_commitish":"master","name":"nightly-**03-02-2018**","body":"Nightly release of ambra-nocigramweb-webhook","draft":false,"prerelease":false}
在pash中,

printf通常是更好的做法。

您甚至可以使用模板:

$ template='{"tag_name":"ambra-nocigramweb-webhook-nightly","target_commitish":"master","name":"nightly-**%s**","body":"Nightly release of ambra-nocigramweb-webhook","draft":false,"prerelease":false}'

$ printf "$template" $(date +%d-%m-%Y)

{"tag_name":"ambra-nocigramweb-webhook-nightly","target_commitish":"master","name":"nightly-**03-02-2018**","body":"Nightly release of ambra-nocigramweb-webhook","draft":false,"prerelease":false}