Bash Scripting Basics
Functions and a Real Backup Script
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
#!/bin/bash
greet() {
echo "Hello, $1"
}
greet Ada
greet Grace
greet()defines the function$1inside the function is the first argument passed to the function- Call it simply by name, with or without arguments
Functions with return values
#!/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:
#!/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}"
localmakes a variable local to the function$(basename "$source")strips the path to just the folder namereturn 1exits the function with an error code
Try it
chmod +x backup.sh- Create a test folder with a few files:
mkdir -p demo && touch demo/a demo/b - Run
./backup.sh demo— thenls ~/backupsand inspect the timestamped copy - Run
./backup.shwith 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.
Advertisement