TutsFx logo

Bash Scripting Basics

Functions and a Real Backup Script

2 min read Last updated 1 hour ago

Functions keep scripts tidy by grouping reusable logic. To finish, we will build a small backup script that uses everything so far.

Defining a function

bash
#!/bin/bash

greet() {
    echo "Hello, $1"
}

greet Ada
greet Grace
  • greet() defines the function
  • $1 inside the function is the first argument passed to the function
  • Call it simply by name, with or without arguments

Functions with return values

bash
#!/bin/bash

is_file() {
    [ -f "$1" ]
}

if is_file "notes.txt"; then
    echo "Yes, it is a file"
fi

The function's [ -f "$1" ] returns 0 (success) or non-zero, which if understands directly.

The backup script

Create backup.sh:

bash
#!/bin/bash
# Simple timestamped backup of a directory

backup_dir() {
    local source=$1
    local dest=$2

    if [ ! -d "$source" ]; then
        echo "Error: $source is not a directory"
        return 1
    fi

    mkdir -p "$dest"
    cp -r "$source" "$dest/$(basename "$source")-$(date +%Y%m%d-%H%M%S)"
    echo "Backed up $source to $dest"
}

if [ -z "$1" ]; then
    echo "Usage: $0 <source-dir> [destination-dir]"
    exit 1
fi

backup_dir "$1" "${2:-$HOME/backups}"
  • local makes a variable local to the function
  • $(basename "$source") strips the path to just the folder name
  • return 1 exits the function with an error code

Try it

  1. chmod +x backup.sh
  2. Create a test folder with a few files: mkdir -p demo && touch demo/a demo/b
  3. Run ./backup.sh demo — then ls ~/backups and inspect the timestamped copy
  4. Run ./backup.sh with no argument — see the usage message

Next steps

You now have the core of shell scripting: shebang, variables, conditionals, loops and functions. Combine them to automate backups, rename batches of files, or monitor logs — the terminal is your tool.

Share:

We value your privacy

We use cookies to enhance your browsing experience, serve personalized ads, and analyze traffic. By clicking "Accept", you consent to our use of cookies. Read our Privacy Policy to learn more.