← Linux and the Command Line
Lesson 50 of 51 · 10 XP
Functions
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
greet() {
echo "Hello, $1!" # $1 — the FUNCTION's first argument
}
greet "Kai" # the call — like an ordinary command
Inside a function, $1, $2, $#, $@ are its own arguments, not the script's.
A function "returns" a result in two ways:
- it prints it, and the calling code picks it up with
$(…):
square() {
echo $(($1 * $1))
}
result=$(square 7) # 49
- an exit code with
return(only a number 0–255, usually 0 means success):
is_even() {
[ $(($1 % 2)) -eq 0 ] # this command's code becomes the function's code
}
if is_even 4; then echo "even"; fi
local makes a variable visible only inside the function. Without it, a function's variables are global:
f() {
local tmp="$1"
...
}
(local isn't in strict POSIX, but bash, dash and BusyBox have it.)
Task. Write a function max that takes any number of numbers and prints the largest one. The script calls it with the script's own arguments.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.