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_SRC

The 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 ...

Get Essential System Administration, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.