bash shell 脚本函数定义(如“f () {}”)中的括号有何用途?它与使用“函数”有什么不同吗?关键词?
我一直想知道它们是做什么用的? 如果你永远无法在其中放入任何东西,那么每次都将它们放入似乎很愚蠢。
function_name () {
#statements
}
另外,将 function
关键字放在函数开头会有什么好处/损失吗?
function function_name () {
#statements
}
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 function
keyword at the start of a function?
function function_name () {
#statements
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
关键字
function
已被弃用,取而代之的是function_name()
以实现 POSIX 规范请注意,
{ }
不是强制性的,因此如果您不打算使用关键字function
(而且您不应该),则>()
是必要的,这样解析器就知道您正在定义一个函数。例如,这是一个合法的函数定义和调用:
The keyword
function
has been deprecated in favor offunction_name()
for portability with the POSIX specNote that the
{ }
are not mandatory so if you're not going to use the keywordfunction
(and you shouldn't) then the()
are necessary so the parser knows you're defining a function.Example, this is a legal function definition and invocation:
第一个示例中需要空括号,以便 bash 知道它是函数定义(否则它看起来像普通命令)。在第二个示例中,
()
是可选的,因为您使用了function
。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 usedfunction
.如果没有
函数
,别名扩展会在定义时发生。例如:然而,使用
function
时,别名扩展不会在定义时发生,因此别名“隐藏”了定义:Without
function
, alias expansion happens at definition time. E.g.:With
function
however, alias expansion does not happen at definition time, so the alias "hides" the definition: