包含双冒号 '::' 的 Bash 脚本函数名称

Jim*_*her 17 bash syntax

我今天遇到了一个 Bash 脚本,它的函数名称中带有双冒号::,例如,file::write()file::read(). 我以前从未在 Bash 脚本中看到过这种语法,当我调用该脚本时,它运行得很好(令我惊讶)。

在我的系统(和在线)上搜索 Bash 的手册页后,我在文档中找不到任何支持函数名称语法的内容。例如,该部分Shell Defined Functions将 shell 函数的语法定义为

function name [()] compound-command [redirection]
Run Code Online (Sandbox Code Playgroud)

然后(在手册中的其他地方)令牌name被定义为

name   A word consisting only of alphanumeric characters and
       underscores, and beginning with an alphabetic character
       or an underscore.  Also referred to as an identifier.
Run Code Online (Sandbox Code Playgroud)

没有任何地方提到函数名的双冒号语法。

到目前为止,我发现的对这种双冒号语法的唯一其他引用是在这个Shell 样式指南(请参阅小节Naming Conventions > Function Names)中,它建议对“包”中的函数名称使用双冒号语法——例如,mypackage::myfunction().

函数名称的这种双冒号语法是 Bash shell 的合法特性,还是可能是未记录的特性?如果它是合法的,它在 Bash 手册中的何处记录?我看了又看,但在手册中找不到任何相关内容。我发现最接近的是::PATH环境变量中使用将当前工作目录添加到搜索路径。

例子

function name [()] compound-command [redirection]
Run Code Online (Sandbox Code Playgroud)

我在三个不同的 Linux 发行版上测试了这个脚本,并且在所有三个发行版上,脚本都打印abc::def到标准输出。

l0b*_*0b0 16

这是文档比实现更严格的情况,可能是为了降低脚步因素。这已经在这里讨论过;另请参阅详尽的测试,确定例如[}{是一个有效的函数名称。

可能还值得注意的是,这abc::def不是一个有效的变量名:

$ abc::def=foo
bash: abc::def=foo: command not found
Run Code Online (Sandbox Code Playgroud)

  • 只是为了清楚地说明 - 不是`file::read` 也不是`[}{` 是有效的posix (4认同)