Bash – Default assignment to a null variable with command substitution

bashcommand-substitutionshellstringvariable substitution

I'm trying to use the syntax:

A=${B:-C}

where A is the variable, B is the value I'm trying to assign, C is the default value if B is null.

Now I want to replace B with the command nc -l 443, so if nc receive a string through port 443, it is assigned to the variable A, else A is set to default value. I wrote the command as:

A=${`nc -l 443`:-NULL}

But I get an error:

-bash: A=${`nc -l 443`:-NULL}: bad substitution

How can I achieve this?

Best Answer

Nested substitution is not available in any modern Bourne-like shells except zsh:

$ print -rl -- ${$(echo):-C}
C
$ print -rl -- ${$(echo 1):-C}
1

In other shells:

A=$(nc -l 443)
A=${A:-C}
Related Question