Functions are blocks of code that exist in memory as named elements. These elements can be created within the shell environment, as well as within the script execution. When a command is issued at the command line, aliases are checked first and, following this, we check for a matching function name. To display the functions residing in your shell environment, you can use the following command:
$ declare -F
The output will vary depending on the distribution you are using and the number of functions you have created. On my Linux Mint, the partial output is shown in the following screenshot:
Using the small -f option, you can display the function and the associated definition. However, if we want to see just a single function definition, we can use the type command:
$ type quote
The previous code example will display the code block for the quote function, if it exists within your shell. We can see the output of this command in the following screenshot:
The quote function in bash inserts single quotes around a supplied input parameter. For example, we can expand the USER variable and display the value as a string literal; this is shown in the following screenshot. The screenshot captures the command and output:
Most code can be represented by a pseudo-code which shows an example layout. Functions are no different and the code to create a function is listed in the following example:
function-name() { <code to execute> }
Also, there is another way of defining functions, like this:
function <function-name> { <code to execute> }
The keyword function is deprecated for portability with the Portable Operating System Interface (POSIX) specification, but it is still used by some developers.
The function is created without a do and done block, as we have used in the previous loops. It is the purpose of the curly brackets to define the code block boundaries.
A simple function to display aggregated system information is shown in the following code. This can be created at the command line and will be resident in your shell. This will not persist the logins and will be lost when the shell is closed or the function is unset. To allow the function to persist, we need to add this to the login script of our user account. The sample code is as follows:
$ show_system() { echo "The uptime is:" uptime echo echo "CPU Detail" lscpu echo echo "User list" who }
We can print the detail of the function similar to the prior instance using the type command; this is shown in the following screenshot:
To execute the function, we simply need to type show_system and we will see the static text and output from the three commands: uptime, lscpu, and who. This is, of course, a very simple function but we can start to add more functionality by allowing parameters to be passed at runtime.