如果我运行这个 shell 脚本,我希望它只需在我的 elasticsearch 索引 backup_timestamps 中添加一个条目。
字段中的“时间戳”应该是当前时间变量。在“system_name”字段中应该是机器当前的主机名变量。
#!/bin/sh
timestamp=`date +"%Y-%m-%d %T"`
system_name=`hostname`
sudo curl -u elastic:PASSWORD -XPOST "https://localhost:9200/backup_timestamps/_doc" --cacert ./certs/ca/ca.crt -H 'Content-Type: application/json' -d '
{
"timestamp": "$timestamp",
"system_name": "$system_name"
}'
echo "("$timestamp" , "$system_name")"
运行此 shell 脚本后,我在 elasticsearch 数据库中得到的是:
{
"_index" : "backup_timestamps",
"_id" : "BybOdYABhPvBW1kMbwKh",
"_score" : 1.0,
"_source" : {
"timestamp" : "$timestamp",
"system_name" : "$system_name"
}
但是我想要得到的是这个:
{
"_index" : "backup_timestamps",
"_id" : "BybOdYABhPvBW1kMbwKh",
"_score" : 1.0,
"_source" : {
"timestamp" : "2022-01-01 12:00:00",
"system_name" : "my-server-or-whatever"
}
另一种方法可以做到这一点,而不会弄乱转义引号,但仅适用于示例中的简单字符串值(即非 JSON 字符串、带有文字引号的字符串、换行符、制表符等):
PAYLOAD_TEMPL='{
"timestamp": "%s",
"system_name": "%s"
}'
PAYLOAD=$(printf "${PAYLOAD_TEMPL}" "${timestamp}" "${system_name}")
sudo curl -u elastic:PASSWORD -XPOST "https://localhost:9200/backup_timestamps/_doc" --cacert ./certs/ca/ca.crt -H 'Content-Type: application/json' -d "$PAYLOAD"
您的 JSON 数据包包含在单引号内。
单引号不允许变量替换,双引号可以:
$ THING=hello
$ echo "$THING"
hello
$ echo '$THING'
$THING
将数据包放在双引号中,看起来像这样:
sudo curl \
-u elastic:PASSWORD -XPOST \
"https://localhost:9200/backup_timestamps/_doc" \
--cacert ./certs/ca/ca.crt \
-H 'Content-Type: application/json' \
-d "{\"timestamp\":\"$timestamp\",\"system_name\": \"$system_name\"}"