Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i use shell variables in .sh file for a elasticsearch curl POST

Hello Stackoverflow community

If i run this shell script i want it to simply add a entry into my elasticsearch index backup_timestamps.

In the field "timestamp" should be the current time varible. And in the field "system_name" should be the current hostname variable of the machine.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#!/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")"

After running this shell script what i get in the elasticsearch db is this:

{
    "_index" : "backup_timestamps",
    "_id" : "BybOdYABhPvBW1kMbwKh",
    "_score" : 1.0,
    "_source" : {
    "timestamp" : "$timestamp",
    "system_name" : "$system_name"
}

But what i want to get is this:

{
    "_index" : "backup_timestamps",
    "_id" : "BybOdYABhPvBW1kMbwKh",
    "_score" : 1.0,
    "_source" : {
    "timestamp" : "2022-01-01 12:00:00",
    "system_name" : "my-server-or-whatever"
}

edit1:

The answer was this:

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\"}"

>Solution :

You have your JSON packet inside single quotes.

Single quotes don’t allow variable substitution, double quotes do:

$ THING=hello
$ echo "$THING"
hello
$ echo '$THING'
$THING

Put your packet in double quotes, which would look something like this:

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\"}"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading