-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
  • 6,303
  • 18
  • 44
  • 76

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
  • 713,503
  • 59
  • 514
  • 593
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
  • 90,796
  • 20
  • 120
  • 197