In shell scripting, functions allow you to group a set of commands together and give them a name, making your code more modular, readable, and maintainable. Functions are a way to encapsulate code so that it can be easily reused and organized within your shell scripts.
Basic syntax and usage of functions in shell scripting:
Syntax:
function_name() {
# Function code
# ...
}
OR
function function_name {
# Function code
# ...
}
Usage:
{
and }
to enclose the code that defines the function.Simple example of a function that greets a person:
In this example, the Hello
function is defined to accept one argument, and it prints a greeting message with the provided name. When you call the function as Hello
, it outputs "Welcome to JanaAI"
Functions can also return values using the return
statement. Here's an example of a function that calculates the sum of two numbers and returns the result:
Output:
Sum: 8
Here are some tips for using functions in shell scripting:
Nested Functions
One of the more interesting features of functions is that they can call themselves and also other functions. A function that calls itself is known as a recursive function.
Following example demonstrates nesting of two functions −
Output:
This is the first function calling...
This is now the second function calling...