Reusable Logic (bash functions)
Concept & Overview
You've written loops and conditionals to automate actions in scripts. But as your scripts grow, copy-pasting the same logic over and over makes them hard to maintain. In bash, we can group commands into reusable functions.
- To define a function, we declare it by name followed by parentheses and curly braces: log_msg() { echo "msg"; }.
- Functions can receive arguments just like shell scripts, which are accessed using local position parameters $1, $2, etc. inside the function body.
- To call a function, simply use its name like any other command: log_msg "Backup started".
backup_helper.sh in your home folder. Define a function named log_msg that prints a message with a timestamp (e.g. log_msg() { echo "[$(date +%T)] $1"; } or similar), and call it at least twice inside the script to log actions. Make it executable and run it.Command Syntax Reference
| Command / Syntax | Description |
|---|---|
log_msg() { echo "$1"; } | Define a function in bash |
Verification Objectives
These conditions will be automatically verified when you run commands inside the interactive terminal simulator:
- ○Create script file "backup_helper.sh" in home
- ○Define the log_msg function inside the script
- ○Make script executable and run it
Ready to complete Quest 102?
Test your skills live in the browser terminal with an emulated Linux filesystem, real-time command evaluation, and instant step-by-step hints.