typestar

Functions in Bash

Arguments by position, locals by declaration, results by echo.

# arguments arrive as $1 $2 ...; local keeps variables contained
greet() {
    local name=${1:-world}
    echo "hello, $name"
}

area() {
    local -i w=$1 h=$2
    echo $(( w * h / 2 ))
}

greet
greet "Ada"
echo "area: $(area 3 4)"

How it works

  1. $1 and $2 are the arguments; ${1:-world} defaults one.
  2. local keeps a variable inside the function.
  3. Callers capture output with $(area 3 4).

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
216
Tokens
52
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 37 seconds.

Type this snippet

Step 1 of 3 in Functions, step 13 of 26 in Language basics.

← Previous Next →

Functions in other languages