How do I echo an empty JSON curly brackets as a default value?

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.


You can cheat and set a variable to be the empty result, and avoid the quoting issues

$ def="{}"
$ echo ${X:-$def}
{}
$ X=y
$ echo ${X:-$def}
y
$ unset X
$ echo ${X:-$def}
{}
$ 

What I frequently do is make use of hex values for characters via printf:

bash-4.3$ echo "${X:-$(printf '\x7B\x7D')}"
{}
bash-4.3$ X="something"
bash-4.3$ echo "${X:-$(printf '\x7B\x7D')}"
something

Slightly verbose, but works without too much stressing out about quotes.

Tags:

Bash

Variable