Functions in shell scripting provide a way to organize code into modular and reusable blocks. This guide covers defining functions, passing arguments, and returning values.
Functions are defined using the function keyword or simply by providing the function name followed by parentheses {}.
#!/bin/bash
# Define a simple function
welcome() {
echo "Welcome to Shell Scripting!"
}
# Call the function
welcomeThis script defines a function named welcome that prints a welcome message when called.
#!/bin/bash
# Define a function with parameters
greet() {
echo "Hello, $1 $2!"
}
# Call the function with arguments
greet "Keval" "Hingu"Here, the function greet takes two parameters and prints a greeting message with the provided arguments.
Functions can accept parameters, allowing dynamic behavior based on user input.
#!/bin/bash
# Function with parameters
multiply() {
result=$(( $1 * $2 ))
echo "Result: $result"
}
# Call the function with arguments
multiply 5 3In this example, the function multiply takes two arguments, multiplies them, and prints the result.
Functions can return values using the return statement.
#!/bin/bash
# Function with return value
calculate() {
local result=$(( $1 + $2 ))
echo "Result from function: $result"
return $result
}
# Call the function and capture the return value
result=$(calculate 8 4)
echo "Result outside function: $result"Here, the function calculate returns the sum of two numbers, and the result is captured when calling the function.
- Defining Functions: Functions are defined using the function keyword or by providing the function name followed by {}.
- Passing Arguments: Functions can accept parameters, allowing dynamic behavior based on user input.
- Returning Values: Functions can return values using the return statement. Experiment with these examples to understand the concepts of defining functions, passing arguments, and returning values in shell scripting.