Functions and Modularization
Section 3: Functions and Modularization
Lesson 1: Defining Functions in Shell Scripts
Functions in shell scripts provide a way to create reusable code blocks and enhance modularization.
1.1 Creating Reusable Code Blocks
#!/bin/bash
# Defining functions in shell scripts
# Function definition
greet_user() {
echo "Hello, $1!"
}
# Calling the function
greet_user "John"
1.2 Passing Arguments to Functions
#!/bin/bash
# Passing arguments to functions
# Function definition
multiply_numbers() {
result=$(( $1 * $2 ))
echo "The result of multiplication is: $result"
}
# Calling the function
multiply_numbers 5 3
Lesson 2: Scope of Variables
Understanding the scope of variables, both local and global, is crucial in shell scripting.
2.1 Local Variables
#!/bin/bash
# Local variables in shell scripts
# Function definition
print_local_variable() {
local localVar="I am a local variable"
echo "$localVar"
}
# Calling the function
print_local_variable
# Attempting to access the local variable outside the function (will result in an error)
echo "$localVar"
2.2 Global Variables
#!/bin/bash
# Global variables in shell scripts
# Declaring a global variable
globalVar="I am a global variable"
# Function definition
print_global_variable() {
echo "$globalVar"
}
# Calling the function
print_global_variable
2.3 Returning Values from Functions
#!/bin/bash
# Returning values from functions
# Function definition
add_numbers() {
local result=$(( $1 + $2 ))
echo "$result"
}
# Calling the function and storing the result in a variable
sum=$(add_numbers 8 4)
echo "The sum is: $sum"
Understanding functions and variable scope is essential for creating well-organized and maintainable shell scripts. In the upcoming sections, we'll explore more advanced scripting techniques and real-world applications.