Functions

The syntax of a function definition is

[ function ] name ( ) command

A function definition is a statement that when run installs a function named name and returns an exit status of zero. The command is normally a list enclosed between braces ({ }).

When name is specified as a simple command, qsh runs command. The arguments to the simple command temporarily become the positional parameters while the function is running. The special parameter 0 is unchanged. By using local, you can declare local variables inside of the function. By using return, you can end the function and resume execution with the next command after the function call.

Examples

Here is an example of a function that provides a qsh interface to the PING CL command.

ping()
{
  # Initialize variables and make them local to this function
  local nbrpkt='' waittime='' intnetadr='' msgmode='' pktlen='' ipttl='' host=''
  local c

  # Process the options
  while getopts c:i:I:qs:T:v c
  do  case $c in
      c)  nbrpkt="NBRPKT($OPTARG)";;
      i)  waittime="WAITTIME($OPTARG)";;
      I)  intnetadr="INTNETADR('$OPTARG')"
          host="*INTNETADR";;
      q)  msgmode='MSGMODE(*QUIET)';;
      s)  pktlen="PKTLEN($OPTARG)";;
      T)  ipttl="IPTTL($OPTARG)";;
      v)  msgmode='MSGMODE(*VERBOSE)';;
     \?)  print -u2 "Usage: ping [-c count] [-i seconds] [-I ipaddr] [-q]" \
            "[-s size] [-T ttl] [-v] hostname"
          return 1;;
      esac
  done

  # Run the command
  shift $OPTIND-1
  system ping ${host:-$1} $intnetadr $nbrpkt $waittime $msgmode $pktlen $ipttl
}