Anthony Kong
Anthony Kong

Reputation: 40874

How to perform string substitution to construct a json string in zsh?

This is my function

function print_doc_json() {
    docId=$1
    echo '{ ":d": { "S": "$(docId)" }}'
}

I want the output of print_doc_json abc123 to be { ":d": { "S": "abc123" }}

However it came out as { ":d": { "S": "$(docId)" }}. The DocId is not substituted.

How can I get a string substitution in string already enclosed in a pair of quote?

Upvotes: 0

Views: 120

Answers (1)

Georg P.
Georg P.

Reputation: 3174

There are two mistakes. First, variable substitution is done like this: ${docId}, not like this: $(docId)

Second, if you enclose a string in single quotes ('), no variable substitution is performed inside - you have to use double quotes ("). Be aware that in this case you must escape the double quotes that you want printed:

function print_doc_json() {
    docId=$1
    echo "{ \":d\": { \"S\": \"${docId}\" }}"
}

Alternatively you can use single quotes outside, but then you must also do the substitution outside:

function print_doc_json() {
    docId=$1
    echo '{ ":d": { "S": "'${docId}'" }}'
}

This is three concatenated strings: '{ ":d": { "S": "', ${docId} and '" }}'.

Upvotes: 1

Related Questions