将命令输出包含到json中

时间:2017-07-12 13:29:33

标签: json bash curl

尝试从bash脚本发送每周备份大小概述,该脚本执行curl发送消息。

echo $(curl -s \
  -X POST \
  --user "aasdfasdfbc:4adgadfgsdfg" \
  https://api.mailjet.com/v3/send \
  -H "Content-Type: application/json" \
  -d '{
    "FromEmail":"noreply@bashdrsh.li",
    "FromName":"Backup Notification",
    "Recipients": [ 
      {
      "Email":"back.upper@bashdrsh.li"
      }
    ],
    "Subject":"['"$host"'] Backup overview",
    "Text-part":"Backup on '"$host"' weekly overview\n\n '"$(find /tmp/backup/2017-07-12/ -maxdepth 1 -type f  -exec ls -hls {} \; | awk '{  printf "%-40s %30s\n", $10, $6 }')"'\n"
  }')

但是find命令总是返回此响应

  find: paths must precede expression: globals-only.7z
  Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec|time] [path...] [expression]
  {
      "FromEmail":"noreply@bashdrsh.li",
      "FromName":"Backup Notification",
      "Recipients": [ 
        {
        "Email":"back.upper@bashdrsh.li"
        }
      ],
      "Subject":"[MYLOCAL] Backup overview",
      "Text-part":"Backup on MYLOCAL weekly overview\n\n \n"
    }

在命令行上运行find命令,它会按预期返回所有内容

# find /tmp/backup/2017-07-12/ -name '*.7z' -exec ls -hls {} \; | awk '{  printf "%-40s %30s\n", $10, $6 }'
/tmp/backup/2017-07-12/globals-only.7z                             7.3K
/tmp/backup/2017-07-12/auth.7z                                      759

如何在邮件中包含一个漂亮的格式化表格?

1 个答案:

答案 0 :(得分:0)

您在find调用中以及稍后在命令行中未使用相同的curl表达式。此外,无需ls& awk

尝试用以下代码替换完整的命令替换:

find /tmp/backup/2017-07-12/ -name '*.7z' -printf "%-40P %30s\n"

为了便于阅读,您可以将其存储到变量中,并使用如下:

output=$(find /tmp/backup/2017-07-12/ -name '*.7z' -printf "%-40P %30s\n")
echo $(curl -s \
  -X POST \
  --user "aasdfasdfbc:4adgadfgsdfg" \
  https://api.mailjet.com/v3/send \
  -H "Content-Type: application/json" \
  -d '{
    "FromEmail":"noreply@bashdrsh.li",
    "FromName":"Backup Notification",
    "Recipients": [ 
      {
      "Email":"back.upper@bashdrsh.li"
      }
    ],
    "Subject":"['"$host"'] Backup overview",
    "Text-part":"Backup on '"$host"' weekly overview\n\n '"$output"'\n"
  }')