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 7In this script, we have defined two functions:
greetfunction: This function takes one argument (person's name) and uses it to print a greeting message. The function is defined with thegreet() { ... }syntax. Inside the function, we useechoto display the greeting message.addfunction: This function takes two arguments (numbers) and calculates their sum. The function is defined with theadd() { ... }syntax. Inside the function, we use a local variableresultto store the sum and then display the result usingecho.
After defining the functions, we call them by providing the required arguments:
We call the
greetfunction with the argument"John", which prints the greeting message"Hello, John!".We call the
addfunction with the arguments5and7, 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