Typorithm · medium

Functions

bash-functionsbashfunctionlocalreturn
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Functions

0%

Scripting

Define a function with name() { ... }; positional params $1, $2 hold its arguments. local scopes a variable to the function, and return sets the exit status (0–255), not a value — echo to "return" data. Call it by writing the name with args.

A bash function is declared with name() { ... } and runs its body whenever you call it. Arguments arrive as positional parameters: $1 is the first, $2 the second, and so on.

local name="$1" copies the first argument into a variable scoped to the function, so it does not leak out and clobber a same-named variable elsewhere.

return only sets the function's exit status — an integer 0–255 where 0 means success. It does not hand back a value, so to "return" data you echo it and let the caller capture the output. You invoke a function by writing its name followed by arguments, like greet "Ada".

01

Define with name() { ... }; args are $1, $2, ...

02

local scopes a variable to the function.

03

return sets the exit status (0–255), not a value; echo to return data.

greet() {
  local name="$1"
  echo "Hello, $name"
  return 0
}
greet "Ada"

Read the implementation

Connect each part of the code to the concept before you type.

1. Define a function

name() { ... } declares a function; the body runs each time you call name.

greet() {

2. Local variable

local scopes name to the function; $1 is the first argument passed to it.

local name="$1"

3. Produce output

echo writes to stdout — the way a function "returns" data for a caller to capture.

echo "Hello, $name"

4. Exit status

return sets the function's exit status (0–255); 0 means success, not a returned value.

return 0

5. Call it

Calling is just the function name followed by arguments, here "Ada" as $1.

greet "Ada"

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Functions: Lesson & Practice · Typorithm | ApplyDjinn