Reputation: 81012
When responding to this comment:
Now I got the the two ":"s are independent, and that's why I couldn't find any document about them. Is the first one needed in this case?
I noticed this paragraph in the spec for the first time:
In the parameter expansions shown previously, use of the <colon> in the format shall result in a test for a parameter that is unset or null; omission of the <colon> shall result in a test for a parameter that is only unset. If parameter is '#' and the colon is omitted, the application shall ensure that word is specified (this is necessary to avoid ambiguity with the string length expansion).
I've seen the matching explanation in the bash reference manual:
When not performing substring expansion, using the form described below (e.g., ‘:-’), Bash tests for a parameter that is unset or null. Omitting the colon results in a test only for a parameter that is unset. Put another way, if the colon is included, the operator tests for both parameter’s existence and that its value is not null; if the colon is omitted, the operator tests only for existence.
before and I understand what the difference is with the colon versions of these expansions.
What confused me just now is this sentence from the spec:
If parameter is '#' and the colon is omitted, the application shall ensure that word is specified (this is necessary to avoid ambiguity with the string length expansion).
I don't understand what ambiguity is possible here if word
is unspecified.
None of the expansion sigils are valid in shell variable names so they cannot possibly start a single-character variable name. If they could then using a parameter
of #
would always be ambiguous without a colon since you could never tell if ${#+foo}
meant the length of the variable foo
or an alternate expansion on #
, etc.
What am I missing here? What ambiguity requires ensuring that word
exist? (I mean not having word
in this expansion is clearly not useful but that's not the same thing.)
Upvotes: 2
Views: 108
Reputation: 531938
-
is also a shell special parameter, whose value is a string indicating which shell options are currently set. For example,
$ echo $-
himBH
${#parameter}
is the syntax for the length of a parameter.
$ foo=bar
$ echo ${#foo}
3
The expression ${#-}
, therefore is ambiguous: is it the length of the value of $-
, or is does it expand to the empty string if $#
is empty? (Unlikely, since $#
is always an integer and cannot be unset, but syntactically legal.) I interpret the spec to meant that ${#-}
should resolve the ambiguity by expanding to the length of $-
(which is what most shells seem to do).
Upvotes: 5