General Recommendations on Functions

We must know what we should keep in mind when using functions in Bash.

We considered the functions in Bash. Here are general recommendations on how to use them:

  1. Choose names for your functions carefully. They should explain the purpose of the functions.

  2. Declare only local variables inside functions. Use some naming convention for them. This solves potential conflicts of local and global variable names.

  3. Do not use global variables in functions. Instead, pass their values to the functions using input parameters.

  4. Do not use the function keyword when declaring a function. It is present in Bash, but the POSIX standard does not have it.

Let’s take a closer look at the last tip. Do not declare functions this way:

function check_license()
{
  declare files=(Documents/*.txt)
  grep "General Public License" "$files"
}

There is only one case when the function keyword is useful. It resolves the conflict between the names of some function and alias.

For example, the following function declaration does not work without the function keyword:

alias check_license="grep 'General Public License'"

function check_license()
{
  declare files=(Documents/*.txt)
  grep "General Public License" "$files"
}

If we have such a declaration, we can call the function by adding a backslash before its name. Here is an example of this call:

\check_license

If we skip the slash, Bash inserts the alias value instead of calling the function. It means that the following command runs the alias:

check_license

There is a low probability that we get the conflict of function and alias names in the script. Each script runs in a separate Bash process. This process does not load aliases from the .bashrc file. Therefore, name conflicts can happen by mistake in the shell mode only.

Get hands-on with 1200+ tech skills courses.