How to use command line shell functions in Linux

Functions, a powerful feature of shell programming, is a group of commands organized by common functionality. These easy-to-manage units, when called return a single value, and do not output anything. Using a function involves two steps:
1. Defining the function
2. Invoking the function

Shell function Vs shell alias

Shell functions and aliases are different on two counts.
– aliases do not take arguments as functions do.
– if a command name is defined as a function and an alias, the alias takes precedence.

Display shell functions

To display the function defines, use the following command:

# typeset -f
list () 
{ 
    ls --color=auto -al | wc -l
}
num () 
{ 
    who | wc -l
}

Defining a Function

A function is defined by using the following general format:

# function [function name] { command; . . . command; }
Note: A space must appear after the opening brace and before the closing brace.

The following example defines a function called num that displays the total number of users currently logged in to the system. The num function runs the who command, whose output is further directed to the wc command.

$ function num { who | wc -l; }

Shell functions in shell scripts

Functions are not only useful in shell scripts but are also used in command-line situations where an alias is unusable. For demonstration, shell functions are run on the command line to illustrate how the functions perform.

The following example creates a function called list that displays the total number of subdirectories and files in the current directory. The list function calls the ls command, whose output is directed to the wc command:

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

Invoking a Function

You can invoke a function by merely entering the function name on the command line or within the shell script.

$ [function name]

For example, to invoke the function num on command line, use the command below.

$ num
Related Post