某些 bash 脚本中使用的“function”关键字是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7917018/
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
What is the 'function' keyword used in some bash scripts?
提问by gavenkoa
For example: Bash-Prog-Intro-HOWTO
function foo() {}
I make search queries in info bashand look in releted chapters of POSIX for functionkeyword but nothing found.
我在info bashPOSIX 的相关章节中进行搜索查询并查找函数关键字,但没有找到。
What is functionkeyword used in some bash scripts? Is that some deprecated syntax?
function某些 bash 脚本中使用的关键字是什么?那是一些不推荐使用的语法吗?
回答by Eugene Yarmash
The functionkeyword is optional when defining a function in Bash, as documented in the manual:
function在 Bash 中定义函数时,关键字是可选的,如手册中所述:
Functions are declared using this syntax:
name () compound-command [ redirections ]or
function name [()] compound-command [ redirections ]
使用以下语法声明函数:
name () compound-command [ redirections ]或者
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.
That said, sometimes you might want to use the functionkeyword to prevent Bash aliasesfrom colliding with your function's name. Consider this example:
通常首选语法的第一种形式,因为它与 Bourne/Korn/POSIX 脚本兼容,因此更易于移植。
也就是说,有时您可能希望使用function关键字来防止 Bash别名与您的函数名称发生冲突。考虑这个例子:
$ 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 wordof the command. With functionthe alias is not expanded:
在这里,'foo'被替换为同名别名的文本,因为它是命令的第一个单词。随着function别名不展开:
$ function foo() { :; }
回答by Newtonx
The functionkeyword is necessary in rare cases when the function name is also an alias. Without it, Bash expands the alias before parsing the function definition -- probably not what you want:
该function关键字是在罕见的情况下,必要时在函数名也是一个别名。没有它,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 functionkeyword, 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.
回答by a'r
The reserved word functionis optional. See the section 'Shell Function Definitions' in the bash man page.
保留字function是可选的。请参阅bash 手册页中的“外壳函数定义”部分。

