在一些 bash 脚本中使用的“ function”关键字是什么?

例如: Bash-Prog-简介

function foo() {}

我在 info bash中进行搜索查询,并在 POSIX 的相关章节中查找 功能关键字,但是什么也没有找到。

在一些 bash 脚本中使用的 function关键字是什么? 是一些不推荐的语法吗?

21327 次浏览

The reserved word function is optional. See the section 'Shell Function Definitions' in the bash man page.

The function keyword is optional when defining a function in Bash, as documented in the manual:

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.
That said, sometimes you might want to use the function keyword to prevent Bash aliases from colliding with your function's name. 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. With function the alias is not expanded:

 $ function foo() { :; }

The function keyword 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:

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:

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.