Variable Scope

Learn how variable scope works with functions.

We'll cover the following...

Variable scope

A naming conflict is a serious problem. It occurs when functions declare their variables in the global scope. As a result, the names of two or more variables can match. If functions access these variables at different moments, they overwrite each other’s data.

Procedural languages provide a feature that resolves naming conflicts. The idea of this mechanism is to restrict the scope of declared variables.

Bash provides the local keyword. Let’s suppose that we declare the variable in some function using this keyword. Then, we can access this variable in the function body only. It means that the function body limits the variable scope.

Here is the latest version of the code_to_error function:

Click on the Run button to view the terminal.

#!/bin/bash

code_to_error()
{
  local _result_variable=$2

  case $1 in
    1)
      eval $_result_variable="'File not found:'"
      ;;
    2)
      eval $_result_variable="'Permission to read the file denied:'"
      ;;
  esac
}


print_error()
{
  code_to_error $1 "error_text"
  echo "$error_text $2" >> debug.log
}


# Calling the function
print_error 1 "readme.txt"
print_error 2 "readme.txt"

We declared the _result_variable ...

Access this course and 1400+ top-rated courses and projects.