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