Bash tilde * substring *扩展 - 无证功能?

时间:2015-07-29 14:13:21

标签: bash

我对这次扩张感到惊讶:

$ echo "${foo:~abc}"

在未设置foo时产生空字符串。我希望它能解析如下:

$ echo "${foo:(~abc)}"

并产生字符串“~abc”。但相反,我发现如果我定义

$ foo='abcdefg'
$ echo "${foo:~abc}"
g

事实上,它在算术上下文中正在使用“abc”。 "${foo:~0}"。同样

$ foo='abcdefg'
$ echo "${foo:~3}"
defg

它可以获得扩展的最后n + 1个字符。我查看了联机帮助页的“参数扩展”部分。我没有看到那里的波浪。 Bash Hackers Wiki仅提及tildes为(也是未记录的)案例修饰符。

此行为至少可以回到3.2.57。

我是否遗漏了记录这种形式的子字符串扩展的地方,或者根本没有记录?

1 个答案:

答案 0 :(得分:8)

它没有记录(您可能会将${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).

这里,~abc是扩展的偏移字段,~是算术表达式中的按位否定运算符。未定义的参数在算术表达式中的计算结果为0,~0 == -1

相关问题