Shell Functions
Bourne shell scripts can define functions. Functions have all the same syntactic features as the scripts themselves, including their own arguments. Within a function, the argument and other shorthand forms refer to its own arguments.
The basic function syntax is:
name( ) {commands}
Here is a sample function from an AIX system, followed by an example of its use:
sserv( )
{
# sserv: function to start a server
# args: $1=daemon pathname; $2!="" means use startsrc
#
if [ $# = 0 ] ; then
echo "sserv: server name required."; return 1
fi
if [ ! -x $1 ] ; then return 1 ; fi
if [ -n "$2" ] ; then
startsrc -s `basename $1`
else
$1
fi
}
...
sserv /sbin/syslogd $USE_SRCThe sserv function starts a
server process on an AIX system, either conventionally from the command
line or via the startsrc command
(which uses the system resource controller subsystem, a general server
management facility). The pathname of the server to start is specified
as sserv’s first argument, and
whether to use startsrc is specified
by the second argument (any non-null value uses it).
The function begins by making sure it was passed one argument; the
function exits this is not the case. Note that return is used instead of exit in functions. Then the function makes
sure the pathname it was passed is executable, and then finally it
starts the daemon.
The example invocation of sserv
uses an environment variable USE_SRC as its second argument. If
USE_SRC is defined, then startsrc will be used; otherwise, only ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access