I'm trying to use the syntax:


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?

  • syntax "A=${B:-C}" is variable expansion in bash but function. Firstly you should assign result of function to variable, than use variable expansion – Costas Jul 26 '16 at 9:15

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

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

In other shells:

A=$(nc -l 443)
| improve this answer | |

In Bash, the line


will assign the value of the variable B to the variable A if B is set and not null. Otherwise the variable A will get the value C, i.e. the string containing the single character C.

What you might want to do:

B=$( some command )

After this, $A will either be the output from some command, if it's not null, or the character C, if it is.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.