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:
#!/usr/bin/env bashecho "Starting backup…"mkdir -p backupscp *.txt backups/echo "Done."
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:
#!/usr/bin/env bashname="$1"if [ -z "$name" ]; thenecho "Usage: ./greet.sh <name>"exit 1fiecho "Hello, $name!"
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:
#!/usr/bin/env bashset -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:
# ┌ 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
- 01A script is a file of commands with a #!/usr/bin/env bash shebang; chmod +x then ./run it.
- 02Read arguments as $1, $2, $@ (all) and $# (count); validate required ones.
- 03Functions organise scripts into named, reusable blocks.
- 04Start real scripts with set -euo pipefail so failures are loud, not silent.
- 05Schedule scripts with cron (crontab -e) — five time fields plus the command.
