Functions

Certainly! Here's an example of a shell script that demonstrates the usage of functions:

#!/bin/bash

# Function to greet a person
greet() {
    echo "Hello, $1!"
}

# Function to add two numbers
add() {
    local result=$(( $1 + $2 ))
    echo "The sum of $1 and $2 is: $result"
}

# Calling the greet function
greet "John"

# Calling the add function
add 5 7

In this script, we have defined two functions:

  1. greet function: This function takes one argument (person's name) and uses it to print a greeting message. The function is defined with the greet() { ... } syntax. Inside the function, we use echo to display the greeting message.

  2. add function: This function takes two arguments (numbers) and calculates their sum. The function is defined with the add() { ... } syntax. Inside the function, we use a local variable result to store the sum and then display the result using echo.

After defining the functions, we call them by providing the required arguments:

  • We call the greet function with the argument "John", which prints the greeting message "Hello, John!".

  • We call the add function with the arguments 5 and 7, which calculates their sum and displays the result as "The sum of 5 and 7 is: 12".

Functions in shell scripts allow you to encapsulate a sequence of commands that perform a specific task. They help make your code modular, reusable, and easier to maintain. You can define functions with any name and include parameters to accept input values. Inside the function, you can use local variables, perform calculations, run conditional statements, and execute any shell commands as needed.

Last updated