5

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?

1
  • 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

7

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}
0
3

In Bash, the line

A=${B:-C}

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 )
A=${B:-C}

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

0

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 .