Linux bash shell 脚本函数定义(如“f () {}”)中使用的括号是什么?它与使用“function”关键字不同吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4654700/
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-08-05 02:26:04  来源:igfitidea点击:

What are the parentheses used for in a bash shell script function definition like "f () {}"? Is it different than using the "function" keyword?

linuxbashfunctionparentheses

提问by Mint

I'v always wondered what they're used for? Seems silly to put them in every time if you can never put anything inside them.

我一直想知道它们是用来做什么的?如果您永远无法在其中放入任何东西,则每次都放入它们似乎很愚蠢。

function_name () {
    #statements
}

Also is there anything to gain/lose with putting the functionkeyword at the start of a function?

function关键字放在函数的开头还有什么好处/损失吗?

function function_name () {
    #statements
}

采纳答案by SiegeX

The keyword functionhas been deprecated in favor of function_name()for portability with the POSIX spec

该关键字function已被弃用,以支持POSIX 规范的function_name()可移植性

A function is a user-defined name that is used as a simple command to call a compound command with new positional parameters. A function is defined with a "function definition command".

The format of a function definition command is as follows:

fname() compound-command[io-redirect ...]

函数是用户定义的名称,用作调用具有新位置参数的复合命令的简单命令。函数是用“函数定义命令”定义的。

函数定义命令的格式如下:

fname() compound-command[io-redirect ...]

Note that the { }are not mandatory so if you're not going to use the keyword function(and you shouldn't) then the ()are necessary so the parser knows you're defining a function.

请注意, the{ }不是强制性的,因此如果您不打算使用关键字function(并且您不应该使用),那么它们()是必要的,因此解析器知道您正在定义一个函数。

Example, this is a legal function definition and invocation:

例如,这是一个合法的函数定义和调用:

$ myfunc() for arg; do echo "$arg"; done; myfunc foo bar
foo
bar

回答by Greg Hewgill

The empty parentheses are required in your first example so that bash knows it's a function definition (otherwise it looks like an ordinary command). In the second example, the ()is optional because you've used function.

在您的第一个示例中需要空括号,以便 bash 知道它是一个函数定义(否则它看起来像一个普通命令)。在第二个示例中,()是可选的,因为您使用了function.