Vikas J
Vikas J

Reputation: 358

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

Upvotes: 2

Views: 140

Answers (2)

chepner
chepner

Reputation: 530922

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:

curl -XPOST -d@- "$URL" <<EOF
{ "AlertType": "IDLE",
  "@timestamp": "$CURDATE"
}
EOF

You should use a tool like jq to generate the JSON for you, though.

date +%F | jq -R '{AlertType: "IDLE", "@timestamp": .}' | curl -XPOST -d@- "$URL" 

or letting json built the timestamp entirely on its own

jq -n '{AlertType: "IDLE", "@timestamp": (now | strftime("%F"))}' | curl ...

Upvotes: 0

Andreas Louv
Andreas Louv

Reputation: 47099

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:

{"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

Upvotes: 5

Related Questions