Search⌘ K

Using Functions in Scripts

Explore how to declare and use functions within Bash scripts to simplify error handling and improve script maintainability. Learn techniques like nested function calls, managing variable scope, and supporting localization by converting error codes into user-friendly messages in different languages.

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 ...