Functions and Scripts
Functions
Reusable Commands
A Bash function groups commands under a name. Calling the function runs its body with its own positional arguments.
Program
Play the script to watch the call pass Ada into the function body.
functions.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash
greet() {
local name="$1"
echo "Hello, $name"
}
greet "Ada"
greet ← defined
3greet() {4 local name="$1"values this stepdefinedgreetcall ← greet Ada
8greet "Ada"values this stepgreet Adacallname ← Ada
3greet() {4 local name="$1"5 echo "Hello, $name"values this stepAdanameAda$1echo "Hello, $name"
4 local name="$1"5 echo "Hello, $name"6}outputHello, Adavalues this stepAdaname
Follow the Call
greet()is defined before it is called.- The call is
greet "Ada". - Inside the function,
$1isAda. local namebecomesAda.- The function prints
Hello, Ada. | place | value | | --- | --- | | call argument |Ada| | function$1|Ada| | localname|Ada| | stdout |Hello, Ada|
function
A function names a reusable group of shell commands.
local
`local` keeps a variable scoped to the current function call.
Exercise: functions.sh
Reproduce Hello, Ada, then identify how the call argument becomes the function's local name.