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
$1and$2are the arguments;${1:-world}defaults one.localkeeps a variable inside the function.- Callers capture output with
$(area 3 4).
Keywords and builtins used here
echolocal
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.
Step 1 of 3 in Functions, step 13 of 26 in Language basics.