我对这次扩张感到惊讶:
$ echo "${foo:~abc}"
Run Code Online (Sandbox Code Playgroud)
foo未设置时产生空字符串.我希望它会像这样解析:
$ echo "${foo:(~abc)}"
Run Code Online (Sandbox Code Playgroud)
并产生字符串"~abc".但是,相反,我发现,如果我做了定义
$ foo='abcdefg'
$ echo "${foo:~abc}"
g
Run Code Online (Sandbox Code Playgroud)
实际上,它在算术上下文中做了"abc"."${foo:~0}".同样
$ foo='abcdefg'
$ echo "${foo:~3}"
defg
Run Code Online (Sandbox Code Playgroud)
它可以获得扩展的最后n + 1个字符.我查看了联机帮助页的"参数扩展"部分.我没有看到那里的波浪.Bash Hackers Wiki仅提到了tildes(也是未记录的)案例修饰符.
这种行为至少可以回到3.2.57.
我只是遗漏了记录这种形式的子串扩展的地方,还是根本没有记录?
这不是无证(你可能已经混乱${foo:~abc}与${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).
Run Code Online (Sandbox Code Playgroud)
这里~abc是扩展的偏移字段,~是算术表达式中的按位求反运算符.未定义的参数在算术表达式中的计算结果为0,并且~0 == -1.