Using Functions in Scripts

Learn how to declare and call functions in scripts.

We'll cover the following

We can declare a function in a script the same way as we do it in the shell. Bash allows both full or one-line form there. For example, let’s come back to the task of handling errors in the large program. We can declare the following function for printing error messages:

print_error()
{
  >&2 echo "The error has happened: $@"
}

This function expects input parameters. They should explain the root cause of the error to a user. Let’s suppose that our program reads a file on the disk. The file becomes unavailable for some reason. Then, the following print_error call reports this problem:

print_error "the readme.txt file was not found"

Let’s suppose that the requirements for the program changed. Now, the program should print error messages to a log file. It is enough to change only the declaration of the print_error function to meet the new requirement. The function body looks like this after the change:

print_error()
{
  echo "The error has happened: $@" >> debug.log
}

This function prints all error messages to the debug.log file. There is no need to change anything at the points where the function is called.

Nested function call

Sometimes, we want to call one function from another. This technique is called a nested function call. Bash allows this and, in general, we can call a function from any point of the program.

Let’s consider an example of a nested function call. Imagine we want to translate the program interface to another language. This task is called localization. It is better to print error messages in a language the user understands, right? We need to duplicate all messages in all languages supported by our program to reach this requirement.

The straightforward solution for localization is to assign a unique code to each error. Using such codes is a common practice in system programming. Let’s apply this approach to our program. Then, the print_error function will receive an error code from the input parameter.

We can write error codes to the log file as it is. However, it is inconvenient for us to interpret these codes. We would need a table to map them into error messages. Therefore, the better solution is to print the text messages to the log file. This means it is our responsibility to convert error codes to text in a specific language. We need a separate function to do this conversion.

The file print-error.sh has a function code_to_error which fulfills the task. We can apply the code_to_error function when printing an error in the print_error body. Here is an example of the print_error function call from some point of our program:

print_error 1 "readme.txt"

Click on the “Run” button and then run the command ./print-error.sh in the terminal below.

Get hands-on with 1200+ tech skills courses.