Lesson 11.5: Functions and a real backup script
Defining and calling functions, giving them arguments, keeping their variables local and returning a status; finding a syntax error with bash -n and fixing it in nano; then reading, checking and running a complete backup script that uses everything from this section: a default argument, a log function, a directory check, set -e, a date-stamped tar archive and an exit code for failures, and how you would schedule it with cron.
20 min
You will learn to
- Define and call a function with arguments
- Use local variables and return codes
- Find syntax errors with bash -n
- Explain what set -e does
- Read and run a complete script that combines variables, conditions and functions
- Know how to schedule a script with cron
Key terms
- Function
- A named block of commands, defined once with name() { … } and called like a command, with its own arguments $1, $2 ….
- local
- Makes a variable exist only inside the function, so it can't overwrite a variable of the same name in the script.
- return
- Ends a function with an exit status (0 success, 1–255 failure). To hand back text, print it and capture it with $( ).
- bash -n
- Reads a script and reports syntax errors without running any command.
- set -e
- Makes the script stop as soon as a command fails, instead of carrying on with a broken state.
- Idempotent
- Safe to run again: running the script twice leaves the system in a sensible state (mkdir -p instead of mkdir, for example).
← Loops: for, while and until · All lessons · Final mission: the 2 a.m. call →