Using Functions in Shell
Learn how to use functions in the shell mode of Bash.
We'll cover the following
Functions in shell
The functions are available in both shell and script execution Bash modes. First, let’s consider how they work in the shell.
Here is the general form of the function declaration:
FUNCTION_NAME()
{
ACTION
}
We can also declare the function in one line this way:
FUNCTION_NAME() { ACTION ; }
The semicolon before the closing curly bracket is mandatory here.
The ACTION
is a single command or block of commands. It is called the function body.
Function names follow the same restrictions as variable names in Bash. We are allowed to use Latin letters, numbers, and the underscore character there. However, the name must not begin with a number.
Declaring a function
Let’s have a look at how to declare and use functions in the shell. Let’s suppose we need statistics about memory usage. These statistics are available through a special file system called proc or procfs. This file system provides the following information:
- The list of running processes.
- The state of the OS.
- The state of the computer hardware.
The default mount point of the procfs is the /proc
path. We can find special files there. They provide us with an interface to the kernel data.
We can read the RAM usage statistics in the /proc/meminfo
file. The cat
utility prints the file contents to the screen:
cat /proc/meminfo
Run the commands discussed in this lesson in the terminal below.
Get hands-on with 1200+ tech skills courses.