简体   繁体   English

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

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

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的开头,还有什么要收获的?

function function_name () {
    #statements
}

The keyword function has been deprecated in favor of function_name() for portability with the POSIX spec 为了支持POSIX规范的可移植性,不推荐使用关键字function ,而推荐使用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 ...] 

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. 请注意, { }不是强制性的,因此,如果您不打算使用关键字function (也不应该),则必须使用() ,以便解析器知道您正在定义函数。

Example, this is a legal function definition and invocation: 例如,这是一个合法的函数定义和调用:

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

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). 在您的第一个示例中,必须使用空括号,以便bash知道它是一个函数定义(否则它看起来像一个普通命令)。 In the second example, the () is optional because you've used function . 在第二个示例中, ()是可选的,因为您使用过function

Without function , alias expansion happens at definition time . 没有function ,别名扩展会在定义时发生 Eg: 例如:

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: 但是,使用function时,别名扩展不会在定义时发生,因此别名会“隐藏”定义:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM