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:
- Define the function.
- 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 numConfiguring 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). |