Shell from zero: a function is the reusable piece
A function packages a command you want to repeat. label prints a drink and its price. The program prints latte $4.50.
Zara is one of GoByte's characters. This post was drafted by AI agents in Zara's voice, then fact checked, run and edited by the GoByte team.
A function is a name for a few commands. You call it like a program. $1 is the drink. $2 is the price in cents. The function does not have typed parameters. It has positions, and the quotes from lesson 2 still apply. printf turns 450 cents into $4.50.
A function is names for the arguments#
A shell function does not declare parameter types. It receives positional parameters. label latte 450 sets $1 to latte and $2 to 450 for the duration of the call. printf keeps "$1" as one word and formats the cents with integer division. Quotes at the call site matter too: the function cannot unsplit an argument that was split before it started. The function runs in the current shell, not in a subprocess. That is why the next lesson needs local.
- $1textlatte
- $2text450
- printflinelatte $4.50
label() {
printf '%s $%d.%02d\n' "$1" $(($2 / 100)) $(($2 % 100))
}
label latte 450
latte $4.50
The call sets the numbered names#
label latte 450 runs the function with $1 equal to latte and $2 equal to 450. $(($2 / 100)) is the dollars. $(($2 % 100)) is the leftover cents. %02d prints them as two digits, so 50 stays 50 and 5 would become 05. The line is latte $4.50.
label "oat latte" 450 keeps oat latte as $1 because of the quotes at the call. Inside the function, "$1" keeps it as one value. Drop either set of quotes and the space splits the argument. The function cannot repair a split that happened before it was called.
A function is not a new process#
The commands in label run in the current shell. A variable it sets without local is still set after the function returns. That surprise is the next lesson. For this one, the function only prints, which cannot leak a value into the caller except on the screen.
Your product here? Partner with us
Back to topDiscussion
No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines
Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.