Functions are named blocks of code which can take arguments. They can be used more than once in a program, and can be used in more than one program.
minmax () { # define a function, no spaces between ( and )
# finds minimum and maximum of integer args
# 3 args: $1 is current min, $2 is current max, $3 is new number
# returns new min, new max
local Min=$(( $3 < $1 ? $3 : $1 )) # if $3 < $1 then Min=$3 else Min=$1
local Max=$(( $3 > $2 ? $3 : $2 )) # if $3 > $2 then Min=$3 else Min=$2
echo $Min $Max # print min and max
} # end of definition
function add { # another way to define a function, no ()
# adds numbers from STDIN, one per line
# 1 arg, $1 is current sum
# returns sum
! read Num && echo $1 && return # if EOF then print sum and return
add $(( $1 + $Num )) # else recursive call with new number added to sum
} # end of definition
typeset # shows your functions
minmax 3 7 9 # call with current min 3, current max 7, new number 9
minmax 3 7 1
minmax 3 7 5
add 0
1
2
3
4
5
Ctrl+d
cat > functions # put function(s) in a file
foo () { echo bar ; }
Ctrl+d
source functions # run in current environment
typeset # shows your functions
foo # execute
rm functions # clean up