$
Learn Linux handbook
en
XP:0
Quest 102Modular
+260 XP

Reusable Logic (bash functions)

Launch Interactive Terminal for This Quest→No installation required • Runs fully in browser

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".

Let's build a modular backup script. Create a script named 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 / SyntaxDescription
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.