Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the 'function' keyword used in some bash scripts?

Tags:

bash

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?

like image 792
gavenkoa Avatar asked Oct 27 '11 14:10

gavenkoa


People also ask

What is function in Bash scripting?

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.

Do you need function keyword Bash?

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.

What is a function in scripting?

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.

What is a keyword in Bash?

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 ]].


1 Answers

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() { :; } 
like image 167
Eugene Yarmash Avatar answered Nov 16 '22 01:11

Eugene Yarmash