0

I need to be able to use ${var} with preserving the single quote as the command requires it. I have tried escaping the single quote by concatenating '"${var}"' but the command gave error as the single quotes didn't get preserved.

$COMMAND '[{"name": "john", "tel": ${var}}]'
Arkadiusz Drabczyk
  • 11,227
  • 2
  • 25
  • 38
wolfeye
  • 25
  • 4
  • Very detailed explanation to a near duplicate problem: https://stackoverflow.com/questions/13799789/expansion-of-variables-inside-single-quotes-in-a-command-in-bash – Paul Mar 04 '22 at 14:29

2 Answers2

1

You should quote this except for "${var}".

var=999
$COMMAND '[{"name": "john", "tel": "'${var}'"}]'
Yuji
  • 525
  • 2
  • 8
0

I think that your command does not "require" single quotes around that JSON string. It's a shell that requires them to treat the entire JSON string as a single word and pass it to $COMMAND.

There are 2 ways to use it in JSON string (I set var to 999):

$ echo command "[{\"name\": \"john\", \"tel\": ${var}}]"
command [{"name": "john", "tel": 999}]

or:

$ echo command '[{"name": "john", "tel": '"${var}"'}]'
command [{"name": "john", "tel": 999}]

However, if your command really requires JSON string enclosed in single quotes do this:

"'[{\"name\": \"john\", \"tel\": ${var}}]'"

Also, [ and ] might not be needed:

"{\"name\": \"john\", \"tel\": ${var}}"  
Arkadiusz Drabczyk
  • 11,227
  • 2
  • 25
  • 38
  • yes i have tried both for using the double quotes it won't work as the command gives parse error the command requires the array to be quoted in single qotes, when i concatenated the variable `'"${var}"'` i lost the single quotes so i got the parse error, i want to be able to preserve the single quotes and use the variable – wolfeye Sep 22 '19 at 22:29
  • to work it need to be exactly `command '[{"name": "john", "tel": 999}]' `without the single quotes a parse error results – wolfeye Sep 22 '19 at 22:30
  • 1
    Would that `"'[{\"name\": \"john\", \"tel\": ${var}}]'"` be ok? – Arkadiusz Drabczyk Sep 22 '19 at 22:32
  • `error: Error parsing JSON:'[{"name": "john", "tel": ".0680000"}]'` though the single quotes was preserved but i got the same parse error – wolfeye Sep 22 '19 at 22:52
  • Well, I have no idea what your command is doing. Can you post it here? And why does your tel. starts with `.`, shouldn't it be a number? – Arkadiusz Drabczyk Sep 22 '19 at 22:55
  • After a little thinking - it might be because this is not correct JSON. Try removing `[` and `]`. – Arkadiusz Drabczyk Sep 22 '19 at 22:58
  • `[ ]` is for an array in JSON, how is that not correct? – Benjamin W. Sep 23 '19 at 00:28
  • @BenjaminW.: You're course right, it's correct. We'd need to see command that OP uses. – Arkadiusz Drabczyk Sep 23 '19 at 09:34