π§ Bash Functions & Scripting β Build Modular, Maintainable Shell Scripts
π§² Introduction β Master the Art of Bash Automation
Bash scripting isnβt just about running commandsβit’s about structuring logic, modularizing tasks, handling inputs, and responding to events. This guide walks you through defining functions, passing parameters, handling script arguments, performing redirection, and even using traps for signal cleanup.
π― In this guide, youβll learn:
- How to define and call functions with parameters
- How to write well-structured scripts using shebang and arguments
- How to redirect output and debug scripts
- How to build interactive select menus
- How to trap signals and control exit behavior
π Topics Covered
| πΉ Topic | π Description |
|---|---|
| π’ Bash: Defining Functions | Use function or () to declare modular code blocks |
| π’ Bash: Function Parameters & Return Values | Pass arguments and use return for exit codes |
π’ Bash: Script Header & Structure (#!/bin/bash) | Add a shebang and organize script logic |
π’ Bash: Script Arguments ($1, $2, etc.) | Handle positional parameters and argument validation |
π’ Bash: Running Scripts (bash script.sh, ./script.sh) | Execute Bash files and make them executable |
| π’ Bash: IO Redirection in Scripts | Redirect output (>, >>, 2>) and input (<) |
π’ Bash: Select Menus (select) | Create user-friendly menu-based interfaces |
π’ Bash: Debugging (set -x, -n, -v) | Enable step-by-step tracing, syntax check, and verbose output |
π’ Bash: Trap, Signals & Exit Codes (trap, exit) | Clean up resources and handle signals or abnormal terminations |
π’ Bash: Defining Functions (function, (), return)
πΉ Syntax:
greet() {
echo "Hello, $1"
}
greet "World"
Or:
function greet {
echo "Hello, $1"
}
β
Use return <code> to set an exit code (0 = success).
π’ Bash: Function Parameters & Return Values
add() {
result=$(( $1 + $2 ))
echo "Sum: $result"
return 0
}
add 3 5
echo "Function exited with code $?"
β
Use $1, $2, etc., inside functions like scripts.
π’ Bash: Script Header & Structure (#!/bin/bash)
Every Bash script should start with:
#!/bin/bash
πΉ Example Layout:
#!/bin/bash
# Define function
say_hello() {
echo "Hello, $1"
}
# Call function
say_hello "User"
β
Save as script.sh, then run using bash script.sh or chmod +x script.sh.
π’ Bash: Script Arguments ($1, $2, $@, $#)
echo "Script name: $0"
echo "First arg: $1"
echo "All args: $@"
echo "Total args: $#"
β Always validate arguments before use:
if [[ $# -lt 1 ]]; then
echo "Usage: $0 filename"
exit 1
fi
π’ Bash: Running Scripts (bash script.sh, ./script.sh)
- Execute directly:
chmod +x script.sh
./script.sh arg1 arg2
- Or use Bash interpreter:
bash script.sh arg1
β
Use the shebang line (#!/bin/bash) to allow direct execution.
π’ Bash: IO Redirection in Scripts (>, <, >>, 2>)
| Symbol | Purpose |
|---|---|
> | Redirect stdout (overwrite) |
>> | Append stdout |
2> | Redirect stderr |
< | Redirect input from file |
&> | Redirect both stdout and stderr |
πΉ Example:
echo "Hello" > out.txt
cat < out.txt
ls /fakepath 2> error.log
π’ Bash: Select Menus (select)
select opt in "Start" "Stop" "Exit"; do
case $opt in
"Start") echo "Starting...";;
"Stop") echo "Stopping...";;
"Exit") break;;
*) echo "Invalid";;
esac
done
β
select is ideal for interactive command-line menus.
π’ Bash: Debugging (set -x, set -n, set -v)
| Option | Description |
|---|---|
-x | Print commands before executing |
-n | Syntax check only (dry run) |
-v | Echo input lines as they’re read |
πΉ Example:
set -x
echo "Debugging this line"
set +x
β Great for troubleshooting long scripts.
π’ Bash: Trap, Signals & Exit Codes (trap, exit)
πΉ Use trap to clean up:
cleanup() {
echo "Cleaning up..."
}
trap cleanup EXIT
πΉ Trap SIGINT:
trap "echo Interrupted!" SIGINT
β
Use exit 0 for success, exit 1 or higher for error conditions.
π Summary β Bash Functions & Scripting
Bash scripting allows you to write modular, maintainable, and reusable code using functions, parameters, and redirection. With traps, menus, and debugging tools, your scripts become production-grade automation tools.
π Key Takeaways:
- Define functions using
()orfunctionfor reusability - Use
$1,$2,$@for arguments in scripts and functions - Add shebang (
#!/bin/bash) to make scripts executable - Redirect input/output and handle errors with redirection operators
- Use
selectfor user choices, andtrapfor signal handling - Enable debugging using
set -xor syntax check withset -n
βοΈ Real-World Applications:
- Scheduled cron job scripts
- Backup and log rotation automation
- User-driven shell tools and server maintenance scripts
β Frequently Asked Questions: Bash Functions & Scripting
β Can a Bash function return a string?
β
Not directly. Use echo inside the function and capture with var=$(func).
β How do I make a Bash script executable?
β
Use:
chmod +x script.sh
β What is the use of trap in Bash?
β
It allows you to run cleanup code on signals like SIGINT, EXIT, etc.
β How do I debug a Bash script?
β
Add set -x at the top or run as:
bash -x script.sh
Share Now :
