In the “plus colon” ${...+:}
expression, only the +
has special meaning in the shell. The colon is just a string value in this case, so we could write that snippet as ${...+":"}
. But, because it is also the first word in a shell command list, it becomes the command :
which always returns true.
Depending on the question if the variable has a value or not, the if
statement becomes either if true false;
or if false;
.
Let's break it down:
For convenience, let's pretend the variable is called var
, and consider the expression:
if ${var+:} false; then ...
If the shell variable $var
exists, the entire expression is replaced with :
, if not, it returns an empty string.
Therefore the entire expression ${var+:} false
becomes either : false
(returning true) or false
(returning false).
This comes down to a test for existence, which can be true even if the variable has no value assigned.
It is very cryptic, but as it happens, is one of the few tests for the existence of a variable that actually works in most, if not all, shells of Bourne descent.
Possible equivalents: (substitute any variable name here for var
)
if [[ ${var+"is_set"} == is_set ]]; then ...
Or, probably more portable:
case ${var+"IS_SET"} in IS_SET) ...;; esac