Functions
Certainly! Here's an example of a shell script that demonstrates the usage of functions:
In this script, we have defined two functions:
greet
function: 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 useecho
to display the greeting message.add
function: This function takes two arguments (numbers) and calculates their sum. The function is defined with theadd() { ... }
syntax. Inside the function, we use a local variableresult
to store the sum and then display the result usingecho
.
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 arguments5
and7
, 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