Bash — Functions
Basic function
#!/bin/bash
greet() {
echo "Hello, $1!"
}
greet "Alice" # Hello, Alice!
Return values
#!/bin/bash
add() {
echo $(($1 + $2))
}
result=$(add 3 4)
echo "Sum: $result" # 7
Return status
#!/bin/bash
is_even() {
[ $(($1 % 2)) -eq 0 ]
}
if is_even 4; then
echo "Even"
else
echo "Odd"
fi
Local variables
#!/bin/bash
my_func() {
local x=10
echo "Inside: $x"
}
my_func
# echo $x # Error: x is not defined
Function with return code
#!/bin/bash
check_file() {
if [ -f "$1" ]; then
return 0 # Success
else
return 1 # Failure
fi
}
if check_file "test.txt"; then
echo "File exists"
else
echo "File not found"
fi
Mini Practice
Write Bash code that:
- Creates a function that takes arguments
- Returns a value via echo
- Uses local variables
- Returns success/failure status
Up Next
In the next lesson, you'll learn about Arguments — handling script arguments.
Related Topics
Frequently Asked Questions about Functions
What is Functions in Bash?
Functions is a fundamental concept in Bash. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Functions?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Functions.
Why is Functions important in Bash?
Functions is essential for Bash development. Understanding this concept will help you write better code and solve real-world problems more effectively.