我使用CURL将数据插入弹性搜索,当我插入固定数据时,它工作正常。我正在尝试获取当前DateTime并分配给变量并使用我想要插入的对象。
这是我的剧本,
while true;
do
echo $i
number=$RANDOM;
let "number %= 9";
let "number = number + 1";
range=10;
for i in {1..18}; do
r=$RANDOM;
let "r %= $range";
number="$number""$r";
done;
curl -XPUT 'http://localhost:9200/nondomain_order/orders/'+$number+'' -d '{
"CustType": null,
"tag": "OrderType:Postpaid",
"GUDeviceID": "0",
"IsAvailable": false,
"GUOrderID": "123",
"OrderID": "3",
"OrderDate": "2015-01-06T15:23:42.7198285+05:30",
"GUAccountID": "15010615234251403",
"CreateUser": "admin",
"CreateDate": "2015-01-01T15:23:42",
"CancelledDate": "1899-01-01T00:00:00",
"CancelledUser": null,
"GUTranID": "15010615234271604",
"TenentID": 39,
"CompanyID": 42,
"ViewObjectID": 0,
"ObjectID": null,
"Status": 2,
"OrderDetails": [
{
"GUPromtionID": "15010519341113508",
"GUOrderID": "15010615234271703",
"ChangeID": 0,
"GUPackageID": "14100112243589402",
"startdate": "2015-01-06T00:00:00"
}
]
我需要获取当前的DateTime并分配给CreateDate。我怎么能这样做?
答案 0 :(得分:7)
在字符串中,更改
"CreateDate": "2015-01-01T15:23:42",
到
"CreateDate": "'"$(date +%Y-%m-%dT%H:%M:%S)"'",
在那里,我终止了'
字符串,并在其中创建了一个"
字符串,其中包含$(date)
。否则,它将不会被执行,而只是作为字符串传递给curl
。
您也可以事先将其分配给变量,并在以后使用它:
now=$(date +%Y-%m-%dT%H:%M:%S)
...
"CreateDate": "'"$now"'",
更改
curl -XPUT 'http://localhost:9200/nondomain_order/orders/'+$number+'' -d '{
到
curl -XPUT 'http://localhost:9200/nondomain_order/orders/'"$number" -d '{
Bash连接只是一个接一个的两个字符串,它们之间没有空格。否则,它会像http://localhost:9200/nondomain_order/orders/+0123456789+
而不是http://localhost:9200/nondomain_order/orders/0123456789
(在这里,我保护number
变量免受双引号扩展的影响,如果它发生变化,则保护其安全性。
答案 1 :(得分:5)
我建议使用 here-doc 来摆脱所有魔法引用,而不是在引号内使用引号。像这样使用curl
:
number=10
dt="$(date --iso-8601=seconds)"
curl -XPUT 'http://localhost:9200/nondomain_order/orders/'$number -d@- <<EOF
{
"CustType": null,
"tag": "OrderType:Postpaid",
"GUDeviceID": "0",
"IsAvailable": false,
"GUOrderID": "123",
"OrderID": "3",
"OrderDate": "2015-01-06T15:23:42.7198285+05:30",
"GUAccountID": "15010615234251403",
"CreateUser": "admin",
"CreateDate": "$dt",
"CancelledDate": "1899-01-01T00:00:00",
"CancelledUser": null,
"GUTranID": "15010615234271604",
"TenentID": 39,
"CompanyID": 42,
"ViewObjectID": 0,
"ObjectID": null,
"Status": 2,
"OrderDetails": [
{
"GUPromtionID": "15010519341113508",
"GUOrderID": "15010615234271703",
"ChangeID": 0,
"GUPackageID": "14100112243589402",
"startdate": "2015-01-06T00:00:00"
}
]
}
EOF
答案 2 :(得分:4)
你可以这样做:
DATE_ISO=$(date +"%Y-%m-%dT%H:%M:%S")
...
curl -XPUT 'http://localhost:9200/nondomain_order/orders/'+$number+'' -d '{
...
"CreateDate": "'"$DATE_ISO"'",
...
}'