简体   繁体   English

在某些bash脚本中使用的'function'关键字是什么?

[英]What is the 'function' keyword used in some bash scripts?

For example: Bash-Prog-Intro-HOWTO 例如: Bash-Prog-Intro-HOWTO

function foo() {}

I make search queries in info bash and look in releted chapters of POSIX for function keyword but nothing found. 我在info bash进行搜索查询,并在POSIX的已重写章节中查找功能关键字,但未找到任何内容。

What is function keyword used in some bash scripts? 在某些bash脚本中使用的function关键字是什么? Is that some deprecated syntax? 那是一些不赞成使用的语法吗?

The function keyword is optional when defining a function in Bash, as documented in the manual : 手册中所述,在Bash中定义函数时, function关键字是可选的:

Functions are declared using this syntax: 使用以下语法声明函数:

name () compound-command [ redirections ]

or 要么

function name [()] compound-command [ redirections ]

The first form of the syntax is generally preferred because it's compatible with Bourne/Korn/POSIX scripts and so more portable. 通常首选语法的第一种形式,因为它与Bourne / Korn / POSIX脚本兼容,因此更加可移植。
That said, sometimes you might want to use the function keyword to prevent Bash aliases from colliding with your function's name. 也就是说,有时您可能希望使用function关键字来防止Bash 别名与您的函数名称冲突。 Consider this example: 考虑以下示例:

$ alias foo="echo hi"
$ foo() { :; }
bash: syntax error near unexpected token `('

Here, 'foo' is replaced by the text of the alias of the same name because it's the first word of the command. 在这里, 'foo'被同名别名的文本替换,因为它是命令的第一个单词 With function the alias is not expanded: 使用function ,别名不会扩展:

 $ function foo() { :; }

The function keyword is necessary in rare cases when the function name is also an alias. 在功能名称也是别名的极少数情况下,必须使用function关键字。 Without it, Bash expands the alias before parsing the function definition -- probably not what you want: 没有它,Bash会在解析函数定义之前扩展别名-可能不是您想要的:

alias mycd=cd
mycd() { cd; ls; }  # Alias expansion turns this into cd() { cd; ls; }
mycd                # Fails. bash: mycd: command not found
cd                  # Uh oh, infinite recursion.

With the function keyword, things work as intended: 使用function关键字,事情可以按预期运行:

alias mycd=cd
function mycd() { cd; ls; }  # Defines a function named mycd, as expected.
cd                           # OK, goes to $HOME.
mycd                         # OK, goes to $HOME.
\mycd                        # OK, goes to $HOME, lists directory contents.

The reserved word function is optional. 保留字function是可选的。 See the section 'Shell Function Definitions' in the bash man page . 请参见bash手册页中的“ Shell函数定义”部分。

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

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