-1

I have the following bash script, I would like to print now inside the echo, I receive an error and not able to make it. Could you please point me out in the right direction?

    $now = date -u +"%Y-%m-%dT%H:%M:%SZ"
    echo '
    {
        "a": {
            "timestamp": $now,
        },
    }
    '
Radex
  • 7,815
  • 23
  • 54
  • 86

2 Answers2

2

First of all your syntax of creating variable now is wrong it should be:

now=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

Then instead of using echo you should use cat that supports here-doc like this:

cat<<-EOF
{
     "a": {
         "timestamp": $now,
     },
}
EOF

This way you don't need to worry about handling quotes and escaping double quotes inside double quotes. Remember that your single quotes in echo don't expand shell variables.

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

You need to have " double quotes to expand shell variables.

Consider:

$ i=22
$ echo "i=$i"
i=22
$ echo 'i=$i'
i=$i

Since you have literal double quotes you want in your interpolated string, you need to backslash escape them:

now=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
echo "{
    \"a\": {
         \"timestamp\": $now,
     },
 }"

Prints:

{
   "a": {
        "timestamp": 2019-10-22T15:52:41Z,
    },
}
dawg
  • 98,345
  • 23
  • 131
  • 206