[英]Shell variable substitution in command
How can i get the below command working. 我如何使以下命令正常工作。
export CURDATE=`date +%Y-%m-%d`
curl -XPOST "http://localhost:9200/test/type" \
-d ' { "AlertType": "IDLE", "@timestamp": $CURDATE }'
I am getting error "reason":"Unrecognized token '$CURDATE': was expecting" How do i get the variable substitution correct in the code above 我收到错误“原因”:“无法识别的标记'$ CURDATE':正在期待”我如何在上面的代码中正确获得变量替换
Single quotes will not expand variables, use double quotes: 单引号不会扩展变量,请使用双引号:
curdate=$(date +'%Y-%m-%d')
curl -XPOST "http://localhost:9200/test/type" \
-d '{"AlertType": "IDLE", "@timestamp": "'"$curdate"'"}'
I also added JSON quotes around the expansion so it becomes something like: 我还在扩展周围添加了JSON引号,因此它变成了类似以下内容:
{"AlertType": "IDLE", "@timestamp": "2016-05-23"}
There shouldn't be any need to export the variable. 不需要导出变量。 And usually only environment variables are written all caps. 通常,只有环境变量写成全大写。 And last I changed the command substitution to $(...)
最后我将命令替换更改为$(...)
'{"AlertType": "IDLE", "@timestamp": "'"$curdate"'"}'
# ^^
# |End singlequotes
# JSON quote
If you're going to hand-write your JSON, it's simpler to read it from standard input than try to embed it in an argument: 如果您要手写JSON,那么从标准输入中读取它比尝试将其嵌入参数中要简单得多:
curl -XPOST -d@- "$URL" <<EOF
{ "AlertType": "IDLE",
"@timestamp": "$CURDATE"
}
EOF
You should use a tool like jq
to generate the JSON for you, though. 不过,您应该使用jq
类的工具为您生成JSON。
date +%F | jq -R '{AlertType: "IDLE", "@timestamp": .}' | curl -XPOST -d@- "$URL"
or letting json
built the timestamp entirely on its own 或者让json
完全自行构建时间戳
jq -n '{AlertType: "IDLE", "@timestamp": (now | strftime("%F"))}' | curl ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.