Using Functions in Shell
Explore how to create and use functions in the Bash shell, including declaring functions, managing variable scope, and calling system info commands. Understand how functions can simplify repetitive tasks, such as retrieving memory statistics from the /proc/meminfo file. Learn to maintain clear function definitions for easier automation and script management.
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 ...