J19
J19

Reputation: 717

Bash expanding vars

I'm running the next command line in Bash shell

TZ=Europe/Madrid; MYVAR='{"timestamp": '$(TZ=$TZ date +%s%3N)', "timestampString": "'$(TZ=${TZ} date -Iseconds)'", "data": "Time Zone: '$TZ'   Date ISO8601: '$(TZ=$TZ date -Iseconds)'"}'; curl --location --request POST 'http://localhost:3000/add' --header 'Content-Type: application/json' --data-raw "${MYVAR}"

The result is:

{"_id":"5f577cf2dbf4243e689ced5e","timestamp":1599569138252,"timestampString":"2020-09-08T12:45:38.000Z","data":"Time Zone: Europe/Madrid   Date ISO8601: 2020-09-08T14:45:38+02:00","__v":0}

The problem here is that

'$(TZ=$TZ date -Iseconds)'

is expanded in a different way in "timestampString" and "data". It should be the same string but both are different

I need to use Bash.

In a single command line, How can expand in both cases as "data"?

Upvotes: 0

Views: 52

Answers (2)

chepner
chepner

Reputation: 531165

You can use date itself to generate the entire string:

MYVAR=$(date +'{"timestamp": %s%3N, "timestampString": "%FT%T.%3NZ", "data": {"Time Zone: '"$TZ"' Date ISO8601: %FT%T%Z"}')

Upvotes: 2

Ivan
Ivan

Reputation: 7277

I'd suggest to split that line like this

TZ=Europe/Madrid

MYVAR='{"timestamp": '
MYVAR+="$(TZ=$TZ date +%s%3N), "
MYVAR+='"timestampString": "'
MYVAR+="$(TZ=$TZ date -Iseconds), "
MYVAR+='"data": "Time Zone": '
MYVAR+="$TZ Date ISO8601: $(TZ=$TZ date -Iseconds)"
MYVAR+='"}'

curl --location --request POST 'http://localhost:3000/add' --header 'Content-Type: application/json' --data-raw "${MYVAR}"

Upvotes: 0

Related Questions