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?
A bash function is a method used in shell scripts to group reusable code blocks. This feature is available for most programming languages, known under different names such as procedures, methods, or subroutines.
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.
A function is a named set of statements that perform a certain task. Functions have unique names. A function can take a set of arguments on which to operate on and return a value that represents the result of the task it has performed.
Some have been discussed already, and others will be used extensively in future chapters. The reserved words (also called keywords) are !, case, coproc, do, done, elif, else, esac, fi, for, function, if, in, select, then, until, while, {, }, time, [[, and ]].
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() { :; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With