This section covers the creation and usage of functions in Bash scripts.
In Bash scripting, functions allow you to group code into reusable blocks. They enhance code readability and maintainability.
To declare a function, use the following syntax:
function_name() {
# function body
echo "Hello, I am a function!"
}
Functions can accept arguments:
greet_user() {
echo "Hello, $1!"
}
# Call the function with an argument
greet_user "John"
Bash functions can return values using return
:
add_numbers() {
local result=$(( $1 + $2 ))
return $result
}
# Call the function and capture the result
add_numbers 5 3
sum=$?
echo "The sum is: $sum"
Call a function by using its name:
function_name
Use local
to declare variables with local scope:
calculate_square() {
local squared=$(( $1 * $1 ))
echo $squared
}
Variables declared outside functions have global scope.
global_var="I am global"
print_global() {
echo $global_var
}
greet() {
echo "Hello, world!"
}
# Call the function
greet
calculate_product() {
local product=$(( $1 * $2 ))
echo "The product is: $product"
}
# Call the function with arguments
calculate_product 4 6
Continue to Part 6: input Output.
Go back to Bash Scripting Guide.
Visit other Developer Guides.