Functions In Depth
Functions take arguments as $1 $2 and $@. local limits variables to the function. return sets the exit status only, so print results and capture them with $( ).
Example
square() { local n=$1; echo $((n * n)); }
greet() { echo "Hello, ${1:-friend}"; }
sum() { local t=0; for n in "$@"; do ((t += n)); done; echo $t; }
echo "$(square 7)"
greet; greet Ada
echo "$(sum 1 2 3 4)"
is_even() { (( $1 % 2 == 0 )); }
is_even 4 && echo "4 even"Result
49 Hello, friend Hello, Ada 10 4 even
Exercise
Limit a variable to the function.
n=1Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.