Skip to main content
Albero Academy

Scripts, Functions & Automation

Package commands into reusable scripts with arguments and functions, make them safe, and schedule them with cron.

Chapter 4Bash15 min readBeginner friendly
  • #Bash
  • #Scripts
  • #Automation

A script is a file of commands you can run and reuse. This final chapter turns everything so far into real automation: scripts that take arguments, functions to organise them, safety flags that stop silent failures, and cron to run them on a schedule.

Your first script

A script starts with a shebang line telling the system which interpreter to use, then your commands. Make it executable, then run it:

backup.sh
#!/usr/bin/env bash
echo "Starting backup…"
mkdir -p backups
cp *.txt backups/
echo "Done."
terminal
chmod +x backup.sh # make it executable (once)
./backup.sh # run it

Arguments

Scripts read arguments as $1, $2, … ($@ is all of them, $# the count). This makes a script reusable across inputs:

greet.sh
#!/usr/bin/env bash
name="$1"
if [ -z "$name" ]; then
echo "Usage: ./greet.sh <name>"
exit 1
fi
echo "Hello, $name!"

Functions

functions
log() {
echo "[$(date +%H:%M:%S)] $1"
}
log "Backup started"
cp *.txt backups/
log "Backup finished"

Writing safe scripts

Start non-trivial scripts with strict mode — it turns silent failures into loud, early ones:

the safety header
#!/usr/bin/env bash
set -euo pipefail
# -e exit on any command failure
# -u error on undefined variables
# -o pipefail a failing command in a pipe fails the whole pipe

Scheduling with cron

cron runs commands on a schedule. Edit your schedule with crontab -e; each line is five time fields plus a command:

a crontab entry
# ┌ minute ┌ hour ┌ day ┌ month ┌ weekday
# │ │ │ │
0 2 * * * /home/albero/backup.sh # run backup.sh every day at 02:00

Practice

Write a backup.sh that takes a target folder as $1, validates it was given (exit with a usage message if not), uses a log function, and starts with the set -euo pipefail header. Then write the cron line to run it nightly.

Key takeaways

  1. 01A script is a file of commands with a #!/usr/bin/env bash shebang; chmod +x then ./run it.
  2. 02Read arguments as $1, $2, $@ (all) and $# (count); validate required ones.
  3. 03Functions organise scripts into named, reusable blocks.
  4. 04Start real scripts with set -euo pipefail so failures are loud, not silent.
  5. 05Schedule scripts with cron (crontab -e) — five time fields plus the command.