Functions in shell scripting


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:

  1. Declare the function by providing a name for it.
  2. Use { and } to enclose the code that defines the function.
  3. Inside the function, you can include any valid shell commands and statements.
  4. Call the function by its name.

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:

  • Give your functions meaningful names.
  • Document your functions using comments.
  • Use functions to break down your scripts into smaller, more manageable pieces.
  • Use functions to encapsulate complex logic.
  • Use functions to return values so that you can use the results of functions in other expressions.
  • Test your functions thoroughly before using them in production.

 

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

Enroll Now

  • Shell Programming
  • Machine Learning