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, 2016 at 9:15

3 Answers 3


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)

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.


If you set a variable in bash using command substitution, you can assign it to a default value when the command fails in the following way:

uid=$(id -u root || echo NULL)
echo $uid
uid=$(id -u nosuchuser || echo NULL)
echo $uid

If you prefer the backticks syntax:

uid=`id -u nosuchuser || echo NULL`

You can silence the error message by redirecting stderr to /dev/null:

uid=$(id -u nosuchuser 2>/dev/null || echo NULL)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .