You are currently viewing Shell Scripting – Function

Shell Scripting – Function

Shell Scripting – Function

Hello Everyone

Welcome to CloudAffaire and this is Debjeet.

In the last blog post, we have discussed array in shell.

In this blog post, we will discuss functions in shell. Like any other programming language, bash also supports functions. A function is a block of code that performs certain actions and can be reused. You can define a function with a list of tasks and then call the function to perform those lists of tasks.

Shell Scripting – Function

Function Definition:

In order to use a function, you have to define the function first. In bash a function can be defined simply using function_name() {} or function function_name {}.

Function Call:

In order to use the function, you need to call the function first. A function can be called simply using the function name. You can call a function anywhere you like for instance directly in bash, inside a bash script or inside another function as long as the function is available and is in the scope of the calling portion.

View Function Definition:

You can view the function definition using the inbuilt type.

Function Deletion:

A function can be deleted using unset -f.

Function Arguments:

You can pass arguments to the function during the function call. Function arguments can be accessed inside a function using $<argument_no>. $@ returns all the function arguments and $# returns the number of arguments passed in the function.

Function Return:

Unlike traditional programming language, a bash function does not support a return value of a function. However, you can assign one integer value to the exit status of the function using return statement and then capture the exit status using $?.

Function Scope:

When you create a function, the function is only available to the session where it is created. If you want to access the function outside the session, you have to define the function in a file and source that file during runtime. Generally, when you call a function inside another function, the calling function can access all the variables from the source function. Function also supports a special type of variable local whose scope is within the function only to restrict this behavior.

Hope you have enjoyed this article, in the next blog post, we will discuss shell expansion.


Leave a Reply