Functions in Bash Scripts
Organize your code with functions, promoting reusability and making your scripts cleaner and easier to maintain.
Functions in Bash Scripts is a free DevOps Bootcamp lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the DevOps Bootcamp learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What are Bash Functions?
In Bash scripting, a function is a block of code that performs a specific task. Think of it as a mini-script within your main script.
Functions help you:
- Reuse Code: Write a piece of logic once and call it multiple times.
- Organize Scripts: Break down complex tasks into smaller, manageable units.
- Improve Readability: Makes your script easier to understand and maintain.
Defining a Simple Function
There are two common ways to define a function in Bash. Both achieve the same result. The most common is the first syntax.
Try running this example. It defines functions but doesn't call them yet!
#!/bin/bash
# Method 1: The most common way
my_first_func () {
echo "Hello from my_first_func!"
}
# Method 2: Using the 'function' keyword
function my_second_func {
echo "Hello from my_second_func!"
}
echo "Functions defined, but not called."Calling Your Functions
Defining a function doesn't execute it. To run the code inside a function, you simply call it by its name, just like any other command.
See how we call my_function after defining it:
#!/bin/bash
my_function () {
echo "This message is from inside the function."
}
echo "Script started."
my_function # Call the function here
echo "Script finished."Local Variables in Functions
By default, variables defined inside a Bash function are global, meaning they can be accessed and modified from anywhere in the script.
To prevent unintended side effects and keep your functions isolated, use the local keyword to declare a variable as local. Local variables only exist within that function.
#!/bin/bash
global_message="I'm a global message"
my_function () {
local func_message="I'm a local message"
global_message="I've been changed by the function!"
echo "Inside func: $func_message"
echo "Inside func: $global_message"
}
echo "Before func: $global_message"
my_function
echo "After func: $global_message"
echo "After func: $func_message (This will be empty)"Passing Arguments to Functions
You can pass information into your functions using arguments, just like with regular shell commands. Inside the function, these arguments are accessed using special variables:
$1,$2,$3...: Individual arguments$#: The total number of arguments$@: All arguments as separate strings
#!/bin/bash
greet_user () {
echo "Hello, $1!"
echo "You are $2 years old."
echo "Total arguments received: $#"
echo "All arguments: $@"
}
echo "Calling greet_user with two arguments:"
greet_user "Alice" 30
echo "\nCalling greet_user with one argument:"
greet_user "Bob"Function Exit Status (Return)
A function, like any command, returns an exit status. By convention, 0 means success, and any non-zero value indicates an error.
You use the return keyword to set this exit status. You can then check it using the special variable $? right after the function call.
#!/bin/bash
check_age () {
local age=$1
if [ "$age" -ge 18 ]; then
return 0 # Success: 18 or older
else
return 1 # Failure: under 18
fi
}
check_age 25
echo "Exit status for 25: $?"
check_age 16
echo "Exit status for 16: $?"
if check_age 20; then
echo "User is an adult."
else
echo "User is a minor."
fiCapturing Function Output
While return sends an exit status, if you want a function to produce a 'value' that can be stored in a variable, the function should echo that value to standard output.
You then capture this output using command substitution, wrapping the function call in $(...).
#!/bin/bash
get_full_name () {
local first_name=$1
local last_name=$2
echo "$first_name $last_name" # Echo the full name
}
name="$(get_full_name "John" "Doe")"
echo "Full name captured: $name"
calculate_area () {
local length=$1
local width=$2
echo $((length * width))
}
area=$(calculate_area 10 5)
echo "Calculated area: $area"Practical Example: A Logger
Here's a practical example of a reusable function: a simple logger. This function can be called throughout your script to print messages with a timestamp, making debugging and tracking easier.
#!/bin/bash
log_message () {
local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
local message="$1"
echo "[$timestamp] $message"
}
log_message "Script execution started."
sleep 1 # Simulate some work
log_message "Processing user data..."
sleep 1
log_message "Operation completed successfully."Function Best Practices
To write clear and maintainable scripts with functions, consider these tips:
- Keep it Simple: Each function should do one thing well.
- Meaningful Names: Use descriptive names like
validate_inputorcreate_backup. - Use
local: Always uselocalfor variables inside functions to avoid conflicts. - Add Comments: Explain what your function does, its arguments, and what it returns.
- Validate Input: If a function expects specific arguments, check them.
Function Argument Check
Test your understanding of how arguments are passed to and accessed within Bash functions.
Functions: Recap & Next Steps
Great job! You've mastered Bash functions.
We covered:
- Defining and calling functions.
- Using
localfor variable scope. - Passing arguments with
$1,$#,$@. - Setting exit status with
return. - Capturing output with
echoand command substitution.
Functions are crucial for writing modular, reusable, and maintainable Bash scripts. Keep practicing to make your scripts more powerful and organized!
Frequently asked questions
Is the “Functions in Bash Scripts” lesson free?
Yes — the full text of “Functions in Bash Scripts” is free to read here on the web, and the DevOps Bootcamp course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the DevOps Bootcamp course, upgrade to CoddyKit PRO.
What will I learn in “Functions in Bash Scripts”?
Organize your code with functions, promoting reusability and making your scripts cleaner and easier to maintain. You practise DevOps Bootcamp with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start DevOps Bootcamp?
No prior experience is required. DevOps Bootcamp on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Functions in Bash Scripts” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this DevOps Bootcamp lesson?
Yes. Every DevOps Bootcamp lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.