Functions: Named Steps
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"; fiThe shortcut
Treat a function as a tiny script inside your script: it has its own $1 and $#, reports success with its exit status, and "returns" text by printing it. So ask of any function: does the caller need a yes/no, or a value? Yes/no means exit status; a value means echo plus $( ).
The call
slugifyruns with one argument, so inside it$1is/home/asha/My Notes/.
Drills
Answer fast — trust the rule.
A script calls hello on line 3 and defines hello() { echo hi; } on line 10. What happens on line 3?
After add() { echo $(( $1 + $2 )); }, what is in x after x=$(add 2 3)?
What happens when a function runs return "hello"?
A script is run with 4 arguments and calls k x y z, where k() { echo $#; }. What prints?
Remember
- Define before calling; arguments arrive as
$1,$2;returnonly reports status. - A function is a tiny script: yes/no through exit status, values through
echoand$( ). - Trap:
return "text"is an error; print the text instead.
