49

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_name () {
    #statements
}
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Mint
  • 14,388
  • 30
  • 76
  • 108

3 Answers3

58

The keyword function has been deprecated in favor of function_name() for portability with the POSIX spec

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.

Example, this is a legal function definition and invocation:

$ myfunc() for arg; do echo "$arg"; done; myfunc foo bar
foo
bar
SiegeX
  • 135,741
  • 24
  • 144
  • 154
13

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). In the second example, the () is optional because you've used function.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 1
    Ah ok, guess that makes sense, it's just in PHP you can put stuff inside the parentheses, so I was curious wether I could do something similar in linux scripting. – Mint Jan 11 '11 at 06:15
  • 3
    @Mint: You can't put anything inside the parentheses and they're not used when calling the function, but you can still pass positional parameters to the function. `foo () { echo "$1"; }; foo hello` – Dennis Williamson Jan 11 '11 at 11:53
7

Without function, alias expansion happens at definition time. E.g.:

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:

alias a=b
function a { echo c; }
b
# => command not found
# Gets expanded to b:
a
# => command not found
unalias a
a
# => c
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
  • 6
    This isn't a feature of the `function` keyword -- it's just aliases working the way they always do, performing textual replacement *on the first word in a line* alone. If someone had created an alias named `function`, it would still be expanded here. – Charles Duffy Feb 20 '20 at 00:15