Bash Functions – Syntax & Examples

Bash Functions

Bash Functions – In this Bash Tutorial, we shall learn about functions in Bash Shell Scripting with the help of syntax and examples.

About Bash Functions

  • Function has to be defined in the shell script first, before you can use it.
  • Arguments could be passed to functions and accessed inside the function as $1, $2 etc.
  • Local Variables could be declared inside the function and the scope of such local variables is only that function.
  • Using functions, you may override builtin commands of Bash Shell.

 

Syntax of function

Any of the following two syntax could be used for defining a function in bash shell scripting.

<function_name>Name of the function. Any word consisting only of alphanumeric characters and under?scores, and beginning with an alphabetic character or an under?score, can be used as a function name.

 

Example Bash Function

 

Example Bash Function – with other Syntax

 

Example – Bash Function with arguments

In this example, we shall learn to pass arguments to functions, and access the arguments inside the function.