Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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:

__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:

_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?

like image 920
helpermethod Avatar asked Dec 10 '12 08:12

helpermethod


People also ask

What does %% mean in bash?

So as far as I can tell, %% doesn't have any special meaning in a bash function name. It would be just like using XX instead. This is despite the definition of a name in the manpage: name A word consisting only of alphanumeric characters and under- scores, and beginning with an alphabetic character or an under- score.

What is $$ in bash script?

$$ is a Bash internal variable that contains the Process ID (PID) of the shell running your script. Sometimes the $$ variable gets confused with the variable $BASHPID that contains the PID of the current Bash shell.

What does D flag do in bash?

In order to check if a directory exists in Bash, you have to use the “-d” option and specify the directory name to be checked. As an example, let's say that you want to check with Bash if the directory /etc exists on your system.

Does Linux use bash?

Bash is the most commonly used CLI shell for Unix-based OSes, including Linux.


1 Answers

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:

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.

like image 77
cwgem Avatar answered Oct 10 '22 16:10

cwgem