In Bash, functions are reusable blocks of code that perform a specific task. They allow you to encapsulate a series of commands into a single unit, which can be invoked and executed multiple times throughout a script. Here’s the syntax for defining and using functions in Bash:
# Function definition
function_name() {
# Commands
}
# Function invocation
function_name
Here’s an example that demonstrates the usage of functions in Bash:
#!/bin/bash
# Function definition
greet() {
echo "Hello, $1!"
}
# Function invocation
greet "Alice"
greet "Bob"
In this example, we define a function called greet
that takes a single argument. Within the function, we use the echo
command to print a greeting message with the provided argument. The function is then invoked twice with different arguments: “Alice” and “Bob”.
When you run this script, it will output:
Hello, Alice!
Hello, Bob!
The function greet
is invoked with the provided arguments, and the greeting messages are printed.
Functions in Bash can also return values using the return
statement. Here’s an example that demonstrates a function returning a value:
#!/bin/bash
# Function definition
add_numbers() {
local sum=$(( $1 + $2 ))
return $sum
}
# Function invocation
add_numbers 5 3
result=$?
echo "Sum: $result"
In this example, the add_numbers
function takes two arguments and calculates their sum. The local
keyword is used to declare a local variable sum
within the function. The return
statement is used to return the value of sum
. The function is then invoked with the arguments 5 and 3, and the result is stored in the variable result
. Finally, the result is printed.
When you run this script, it will output:
Sum: 8
The function add_numbers
calculates the sum of 5 and 3, returns the result, and the script prints the sum.
Functions in Bash provide a way to organize and reuse code, making scripts more modular and easier to maintain. They allow you to define custom behaviour and perform specific tasks within your script.