Text-only | Table of Contents (frame/ no frame) |
(23) Functions |
![]() ![]() ![]() |
sh
allow you define shell functions, which are visible only
to the shell script and can be used like any other command. Shell functions take precedence over
external commands if the same name is used. Functions execute in the same process as the caller,
and must be defined before use (appear earlier in the file). They allow a script to be broken
into maintainable chunks, and encourage code reuse between scripts.
identifier() { list; }
function identifier { list; }
A function may read or modify any shell variable that exists in the calling script. Such variables are global.
(ksh and bash only) Functions may also declare local variables in the function using typeset
or
declare
.
Local variables are visible to the current function and any functions called by it.
return [n]
, exit [n]
return
, the function returns when it reaches the end, and the value is the
exit status of the last command it ran.
Example:
die() { # Print an error message and exit with given status # call as: die status "message" ["message" ...] exitstat=$1; shift for i in "$@"; do print -R "$i" done exit $exitstat }
Example:
[ -w $filename ] || \ die 1 "$file not writeable" "check permissions"
Example: Backgrounded function call. ex12 display, text
Example:
vprint() { # Print or not depending on global "$verbosity" # Change the verbosity with a single variable. # Arg. 1 is the level for this message. level=$1; shift if [[ $level -le $verbosity ]]; then print -R $* fi } verbosity=2 vprint 1 This message will appear vprint 3 This only appears if verbosity is 3 or higher
.
" operator.
Functions may generate output to stdout, stderr, or any other file or filehandle. Messages to stdout
may be captured by command substitution (`myfunction`
, which provides another way for a function to
return information to the calling script. Beware of side-effects (and reducing reusability)
in functions which perform I/O.
functions.src last modified Mar 11, 2005 | Introduction | Table of Contents (frame/no frame) |
Printable (single file) |
© Dartmouth College |