Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the parentheses used for in a bash shell script function definition like "f () {}"? Is it different than using the "function" keyword?

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 } 
like image 475
Mint Avatar asked Jan 11 '11 06:01

Mint


People also ask

What are parentheses in bash?

Parentheses ( () ) are used to create a subshell. For example: $ pwd /home/user $ (cd /tmp; pwd) /tmp $ pwd /home/user. As you can see, the subshell allowed you to perform operations without affecting the environment of the current shell.

Why do bash functions have parentheses?

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 .

What is the purpose of the double parentheses (( )) in the scripts?

Similar to the let command, the (( ... )) construct permits arithmetic expansion and evaluation. In its simplest form, a=$(( 5 + 3 )) would set a to 5 + 3, or 8.

What is the use of F in shell script?

Generally, the -f command stands for files with arguments. The command specifies the associated input to be taken from a file or output source from a file to execute a program. The f command uses both -f and -F (follow) to monitor files. In a shell script, -f is associated with the specified filename.


1 Answers

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 
like image 54
SiegeX Avatar answered Oct 06 '22 18:10

SiegeX