bash - 为什么要为私有函数加双下划线 (__)?为什么 (_) 用于 bash 完成功能?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13797087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:58:52  来源:igfitidea点击:

bash - Why double underline (__) for private functions? Why (_) for bash completion functions?

bashfunctioncoding-style

提问by helpermethod

When you look at bash functions shipped with your Linux of choice, you often see that private(private in the sense of a recommendation) functions are written like this:

当您查看您选择的 Linux 附带的 bash 函数时,您经常会看到private(推荐意义上的私有)函数是这样编写的:

__private_func() {
    :
}

So, you first wonder why not just one underscore (_) for private functions... then you see that bash completion functions usually start with a single underscore, usually calling private functions with a double underscore like in the example before:

因此,您首先想知道为什么_私有函数不只有一个下划线 ( ) ……然后您会看到 bash 完成函数通常以单个下划线开头,通常调用带有双下划线的私有函数,如前面的示例:

_complete_func() {
    __private_func
}

What I would like to know is: What is the reasoning about this? And is there some convention about how to prefix private functions?

我想知道的是:这是什么原因?是否有一些关于如何为私有函数添加前缀的约定?

采纳答案by cwgem

I looked over the bash man page and the POSIX shell standard, but was not able to locate anything regarding this naming convention. That said, there is the use of the underscore for indicating reserved or internal names in C. To quote the libc manual on reserved names:

我查看了 bash 手册页和POSIX shell 标准,但无法找到有关此命名约定的任何内容。也就是说,在 C 中使用下划线来指示保留名称或内部名称。引用有关保留名称libc 手册

In addition to the names documented in this manual, reserved names include all external identifiers (global functions and variables) that begin with an underscore (‘_') and all identifiers regardless of use that begin with either two underscores or an underscore followed by a capital letter are reserved names

除了本手册中记录的名称之外,保留名称还包括以下划线 ('_') 开头的所有外部标识符(全局函数和变量)以及所有以两个下划线或一个下划线后跟大写字母是保留名称

The main logic for this naming convention is:

这个命名约定的主要逻辑是:

so that the library and header files can define functions, variables, and macros for internal purposes without risk of conflict with names in user programs

以便库和头文件可以为内部目的定义函数、变量和宏,而不会有与用户程序中的名称冲突的风险

It also would have the benefit of being able to grep between "private" and "public" functions (which I put in quotes because a user can call either form regardless of naming) easily.

它还具有能够轻松地在“私有”和“公共”函数之间进行 grep 的好处(我将其放在引号中,因为用户可以不管命名如何调用任何一种形式)。