![写法 `function Name { ...; 的区别}`, `名称 () { ...; }` 和 `函数名称 () { ...; }` 在 bash](https://linux22.com/image/78747/%E5%86%99%E6%B3%95%20%60function%20Name%20%7B%20...%3B%20%E7%9A%84%E5%8C%BA%E5%88%AB%7D%60%2C%20%60%E5%90%8D%E7%A7%B0%20()%20%7B%20...%3B%20%7D%60%20%E5%92%8C%20%60%E5%87%BD%E6%95%B0%E5%90%8D%E7%A7%B0%20()%20%7B%20...%3B%20%7D%60%20%E5%9C%A8%20bash%20.png)
您可以通过多种方式编写 bash 函数:
function JoinStrings {
...;
}
或者
function JoinStrings () {
...;
}
或者
JoinStrings () {
...;
}
这些功能有什么区别吗?为什么 bash 中有 3 种不同的方法来编写函数? (还有更多的方法来编写函数吗?)
答案1
man bash
说:
Shell Function Definitions
A shell function is an object that is called like a simple command and exe‐
cutes a compound command with a new set of positional parameters. Shell
functions are declared as follows:
name () compound-command [redirection]
function name [()] compound-command [redirection]
This defines a function named name. The reserved word function is
optional. If the function reserved word is supplied, the parentheses
are optional. The body of the function is the compound command com‐
pound-command (see Compound Commands above). That command is usually
a list of commands between { and }, but may be any command listed
under Compound Commands above. compound-command is executed whenever
name is specified as the name of a simple command. When in posix
mode, name may not be the name of one of the POSIX special builtins.
Any redirections (see REDIRECTION below) specified when a function is
defined are performed when the function is executed. The exit status
of a function definition is zero unless a syntax error occurs or a
readonly function with the same name already exists. When executed,
the exit status of a function is the exit status of the last command
executed in the body. (See FUNCTIONS below.)
简而言之,没有什么区别。