A.6 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 one argument will be passed to sserv.

A.6.1 bash Local Variables

bash functions may define local variables variables whose scope is limited to the function and have no meaning in or effect on the script as a whole via its local command, which takes the desired variable names as its arguments. Note also that any variables declared within a function are automatically local variables.



Essential System Administration
Essential System Administration, Third Edition
ISBN: 0596003439
EAN: 2147483647
Year: 2002
Pages: 162

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net