The function
keyword was introduced in ksh. The traditional Bourne shell only had the foo ()
syntax, and POSIX standardizes only the foo ()
syntax.
In ATT ksh (but not pdksh), there are a few differences between functions defined by function
and functions defined with the Bourne/POSIX syntax. In functions defined by function
, the typeset
keyword declares a local variable: once the function exits, the value of the variable is reset to what it was before entering the function. With the classic syntax, variables have a global scope whether you use typeset
or not.
$ ksh -c 'a=global; f () { typeset a=local; }; f; echo $a'
local
$ ksh -c 'a=global; function { typeset a=local; }; f; echo $a'
global
Another difference in ksh is that functions defined with the function
keyword have their own trap context. Traps defined outside the function are ignored while executing the function, and fatal errors inside the function exit only the function and not from the whole script. Also, $0
is the function name in a function defined by function
but the script name in a function defined with ()
.
Pdksh does not emulate ATT ksh. In pdksh, typeset
creates locally-scoped variables regardless of the function, and there are no local traps (though using function
does make some minor differences — see the man page for details).
Bash and zsh introduced the function
keyword for compatibility with ksh. However in these shells function foo { … }
and foo () { … }
are strictly identical, as is the bash and zsh extension function () { … }
. The typeset
keyword always declares local variables, and traps are not local (you can get local traps in zsh by setting the local_traps
option).
function baz { echo "baz"; }
. See Bashism in GreyCat's wiki. – manatwork Apr 26 at 11:34