How to Use Functions in Korn Shell (ksh)

Using Korn Shell Functions

Functions are a powerful feature of shell programming used to construct customized commands. A function is a group of UNIX commands organized as separate routines. Using a function involves two steps:

  1. Define the function.
  2. Invoke the function.

Defining a Function

A function is defined using the general format:

function_name { command; . . . command; }

Function Examples

The following example creates a function called num to perform the who command, directing the output to the wc command to display the total number of users currently logged on the system:

$ function num { who | wc -l; }
$ num
9

The following example creates a function called list to perform the ls command, directing the output to the wc command to display the total number of subdirectories and files in the current directory:

$ function list { ls -al | wc -l; }
$ list
34

To display a list of all functions, use the following command:

$ typeset -f
function list
{
ls -al | wc -l; }

function num
{
who | wc -l; }

To display just the function names, use the following command:

$ typeset +f
list
num