Functions
Define some shell code by name and store it in the shell's memory, to
be invoked and run later.
- A function is saved in memory when it is defined (i.e., in a shell
script)
- A function may also be loaded (from a directory in FPATH) into memory
when invoked:
FPATH=~/myfunctions autoload fname
- Functions are run in the process that invokes them
- To see all functions defined in your login session, type functions
- To delete a function definition, type unset -f fname
Function Syntax
The first form is prefered.
function fname {
shell commands
}
or...
fname () {
shell commands
}
Example:
function termsettings {
echo "Terminal settings are:"
echo "TERM = $TERM"
echo "EDITOR = $EDITOR"
echo "stty settings:"
stty -a
}
Function Variables
Shell functions use positional parameters just like shell scripts do.
- Functions are invoked with arguments on the command line, separated
by spaces
- Positional parameters and other special variables refer to these arguments:
$0 $1 ${10} $* $@ $#
- These variables are local to the function
- User-defined variables are global (default)
Example
(from Learning the Korn Shell, p. 93)
function afunc {
print in function $0: $1 $2
var1="in function"
}
var1="outside of function"
print var1: $var1
print $0: $1 $2
afunc funcarg1 funcarg2
print var1: $var1
print $0: $1 $2
Command Precedence
Shell looks for the definition of a command in the following order:
- Keywords (e.g. function, if, for)
- Aliases
- Built-ins (e.g. cd, whence)
- Functions
- Shell scripts and other executable programs (search in directories
listed in PATH)
To see the source of a command, type
whence -v commandname
Shell Input
read
The read command reads one line of text from the standard input, and
assigns it to the specified variable(s).
- The input line is broken up into fields, separated by spaces or tabs
- Separate fields are assigned to separate variables
- If there are more fields than variables, the last variable is assigned
the remainder of the line
- If there are more variables than fields, extra variables are assigned
a null value
- Exit status is 0 unless the input file is not open, or an end-of-file
is encountered.
More Control-Flow Commands
while
while test-command
do
commands
done
Example:
while read line
do
echo $line >> outfile
done
until
until test-command
do
commands
done
Example:
secretname="Snow White"
name=none
until [[ ${name} = ${secretname} ]]
do
echo "Guess a name: \c"
read name
done
echo "Good guess!"
Interrupting Loops
The break and continue commands may be used to skip
over parts of the loop.
- break transfers control to the statement after the done statement
- continue transfers control to the done statement