In programming languages, variables are named containers that store values. They are the backbone of any program, allowing us to create dynamic scripts. In Bash scripting, we have two main types of variables – Global and Local. This article will offer a deep dive into these types, showing you how to declare, use, and manipulate them.
Introduction to Bash Variables
In Bash (Bourne Again SHell), a shell for the GNU operating system, variables are utilized to store data. Their names are case-sensitive and traditionally are capitalized, although lower case names are also allowed.
To assign a value to a variable, we use the equals sign (=) with no spaces around it. For instance:
This assigns the string “TecAdmin” to the variable `NAME`.
Once a variable is assigned, we can access its value using a dollar sign ($). The following command will print the variable `NAME` to the console:
By default, every variable we create in Bash is global. This means it’s accessible anywhere in the script, regardless of scope. They can be used in any function, loop, or conditional statement within the script.
In the script above, `GLOBAL_VAR` is a global variable, and it’s accessible within the function test.
Unlike global variables, local variables are confined to the block of code or function in which they are declared. Outside of that block, the variable is not recognized.
We create a local variable in Bash by using the `local` keyword.
Here’s an example:
In this script, `LOCAL_VAR` is defined within the function test. When we try to
echo LOCAL_VAR outside of the function, it returns nothing since it’s not recognized outside of its local scope.
Interaction between Local and Global Variables
Let’s understand what happens when we use a local variable with the same name as a global variable.
In this script, the function test declares a local variable `VAR` that shares the same name as a global variable. Within the function, the local variable takes precedence over the global one, but outside the function, the global variable maintains its value. This concept is called ‘variable shadowing’.
Understanding variable scopes and how to work with local and global variables is fundamental to scripting in Bash. It allows us to control where variables can be accessed and modified, providing a layer of security to our scripts. Global variables are accessible anywhere in the script, whereas local variables can only be used in the block of code or function where they’re declared. Always remember to use the most restrictive scope possible for your variables to avoid unexpected behavior in your scripts.