Functions: Named Steps
A function is a named block of commands, defined before it is called, that receives its own positional arguments and reports an exit status with return, while any data it produces is printed and captured.
Separate a function's printed data from its exit status and arguments.
backup.sh now prints time-stamped messages in six places, each a copy of the same printf line, and works out an archive name in two places. When you want to change the time format, you have six lines to find. A function gives a block of commands a name, so it is written once and called anywhere.
The rule
Define before calling; arguments arrive as
$1,$2;returnonly reports status.
log() {
printf '[%s] %s\n' "$(date +%T)" "$*" >&2
}
slugify() {
local base="${1%/}"
base="${base##*/}"
echo "${base// /_}"
}
log "Starting backup"
name="$(slugify "$HOME/My Notes")" # My_Notes
log "Archive name: $name"- Define with
name() { commands; }. Bash reads top to bottom, so the definition must come before the first call. - Call it like any command: its name, then its arguments.
- Inside,
$1,$2,"$@"and$#are the function's own arguments, not the script's. ($0is still the script name.) return Nends the function with exit status N (0 to 255), so functions work withif,&&and||. Without it, the status is that of the last command inside.- To hand back data, the function prints it and the caller captures it with
$( ).return "My_Notes"is an error: return only takes a number.
is_backup() { [[ "$1" == *.tar.gz ]]; } # status is the test's status
if is_backup "$file"; then log "Found $file"; fi