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 ${...+":"}
.
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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…