114

For example: 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.

What is function keyword used in some bash scripts? Is that some deprecated syntax?

3 Answers 3

143

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() { :; }
5
  • 12
    @gavenkoa Yes. When using the 'function' keyword, Bash function declarations are not compatible with Bourne/Korn/POSIX scripts. Commented Oct 27, 2011 at 19:41
  • 1
    Note that in Korn shell there are differences in the scope of typedef'ed variables between the two ways of declaring functions (since scoped variables are not POSIX).
    – cdarke
    Commented Jun 29, 2017 at 7:27
  • How would you differentiate between a call to the foo alias and the foo function? Commented Feb 13, 2019 at 1:18
  • @AaronFranke You can use the type built-in, e.g. type -a foo. Commented Feb 13, 2019 at 5:13
  • 4
    If you don't care about Bourne/Korn/POSIX scripts, you should declare the bash function with function function_name
    – MaXi32
    Commented Oct 18, 2020 at 4:31
86

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.
0
13

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.