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; }
Note: A space must appear after the first brace and before the closing brace.

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
Note: If a command name is defined as a function and an alias, the alias takes precedence.

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

Configuring the Shell Environment

The shell secondary prompt string is stored in the PS2 shell variable, and you can customize it as needed.

$ PS2="somethings missing >" $ echo $PS2 somethings missing > $ In this example, the secondary prompt displays the message that the command line is incomplete.
Note: To have this secondary shell prompt appear in every shell, it must be included in the user's Korn shell initialization file (usually named .kshrc).

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA * Time limit is exhausted. Please reload the CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.