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

发布于 2024-10-11 08:27:53 字数 247 浏览 8 评论 0原文

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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

药祭#氼 2024-10-18 08:27:54

关键字 function 已被弃用,取而代之的是 function_name() 以实现 POSIX 规范

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

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

fname() 复合命令[io-redirect ...]

请注意,{ } 不是强制性的,因此如果您不打算使用关键字 function(而且您不应该),则 >() 是必要的,这样解析器就知道您正在定义一个函数。

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

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

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

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 ...]

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.

Example, this is a legal function definition and invocation:

$ myfunc() for arg; do echo "$arg"; done; myfunc foo bar
foo
bar
哆啦不做梦 2024-10-18 08:27:54

第一个示例中需要空括号,以便 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 used function.

偏闹i 2024-10-18 08:27:54

如果没有函数,别名扩展会在定义时发生。例如:

alias a=b
# Gets expanded to "b() { echo c; }" :
a() { echo c; }
b
# => c
# Gets expanded to b:
a
# => c

然而,使用 function 时,别名扩展不会在定义时发生,因此别名“隐藏”了定义:

alias a=b
function a { echo c; }
b
# => command not found
# Gets expanded to b:
a
# => command not found
unalias a
a
# => c

Without function, alias expansion happens at definition time. E.g.:

alias a=b
# Gets expanded to "b() { echo c; }" :
a() { echo c; }
b
# => c
# Gets expanded to b:
a
# => c

With function however, alias expansion does not happen at definition time, so the alias "hides" the definition:

alias a=b
function a { echo c; }
b
# => command not found
# Gets expanded to b:
a
# => command not found
unalias a
a
# => c
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文