I was surprised that this expansion:
$ echo "${foo:~abc}"
yielded the empty string when foo
was unset. I expected that it would parse like this:
$ echo "${foo:(~abc)}"
and yield the string "~abc". But instead, I found that if I did define
$ foo='abcdefg'
$ echo "${foo:~abc}"
g
In fact, it's taking "abc" in arithmetic context and doing. "${foo:~0}"
. Likewise
$ foo='abcdefg'
$ echo "${foo:~3}"
defg
It gets you the last n+1 characters of the expansion. I looked in the "Parameter Expansion" section of the manpage. I see no mention of tildes there. Bash Hackers Wiki only mentions tildes as (also undocumented) case modifiers.
This behavior goes back to at least 3.2.57.
Am I just missing where this form of substring expansion is documented, or is it not documented at all?
It's not undocumented (you may have been confusing ${foo:~abc}
with ${foo-~abc}
).
${parameter:offset}
${parameter:offset:length}
Substring Expansion. Expands to up to length characters of the
value of parameter starting at the character specified by off-
set. [...] If length is omitted, expands to the substring of the
value of parameter starting at the character specified by offset
and extending to the end of the value. length and offset are
arithmetic expressions (see ARITHMETIC EVALUATION below).
Here, ~abc
is the offset field of the expansion, and ~
is the bitwise negation operator in the arithmetic expression. An undefined parameter evaluates to 0 in an arithmetic expression, and ~0 == -1
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments