Bash – How to echo an empty JSON curly brackets as a default value

bashvariable

I can't seem to get an empty JSON {} to echo if an envvar is missing. I either have a trailing } in the output if set, or the escape displays.

bash-3.2$ unset X
bash-3.2$ echo "${X:-{}}"
{}
bash-3.2$ X=y
bash-3.2$ echo "${X:-{}}"
y}
bash-3.2$ echo "${X:-{\}}"
y
bash-3.2$ unset X
bash-3.2$ echo "${X:-{\}}"
{\}
bash-3.2$ echo "${X:-'{}'}"
'{}'
bash-3.2$ X=z
bash-3.2$ echo "${X:-'{}'}"
z

How do I escape it correctly?

Best Answer

Quote your braces:

bash-3.2$ echo "${X:-"{}"}"
{}
bash-3.2$ X=y
bash-3.2$ echo "${X:-"{}"}"
y
bash-3.2$ unset X
bash-3.2$ echo "${X:-"{}"}"
{}

Inner double quotes are required here, which looks funny but is syntactically fine.

Single quotes won't work, and I'm not entirely sure why not. This is real nested quoting, not end-and-resume, which you can verify by putting spaces in. Double will work fine though.

Related Question