Variable Scopes in Bash

In Bash scripting, variable scope is a crucial context that determines the visibility of variables. It allows you to manage the variables’ usage, prevent unexpected conflicts, control data encapsulation, and organize codes in a modulated way. Therefore, read the following article to get a wholesome concept of variable scopes in Bash.

Key Takeaways

  • Learning about the context of variable scopes in Bash.
  • Learning what are the local and global variables in Bash.
  • Understanding the concept of the unbound variable in Bash.

Free Downloads

What is Variable Scope in Bash?

The fundamental concept of variable scope is the regional context within a Bash script or program that represents a variable’s existence and use. This scope dictates where the variables are valid and you can easily access and modify them within the code. This essential feature actually controls the data encapsulation within functions and prevents unintended naming conflicts within Bash programs.

2 Basic Types of Variable Scopes Bash Provide

In the following section, you will find two primary types of variable scopes that affect a variable’s existence and accessibility in different ways within the Bash scripts. Let’s see a detailed demonstration:

Type 01: Local Scope for Variable

Local scope for variable defines a variable that is accessible only inside a function or code block where they are declared. Even you cannot access the variable from any other function in which it is not properly defined. These local variables exist only during function execution. As they exist for a limited lifetime, once the function terminates, you can no longer access their values. Following is a step-by-step example regarding this:

Steps to Follow >

➊ Go to Ubuntu Terminal, open a script in the nano text editor by running the following command:

nano local.sh
EXPLANATION
  • nano: A text editor.
  • local.sh: This is a script. Here, I have named the script ‘local.sh’. You can name any of your choices.

Opening the file in Nano text editor

➋ Now, write the following script inside the editor:

Script (local.sh) >

#!/bin/bash

function1() {
  local local_variable="Hello, Linux!"
  #Accessing the local variable ‘local_variable’ inside the functio
  echo "Local variable inside the function: $local_variable"
}
function1

#Accessing the local variable ‘local_variable’ outside the function
echo "Local variable outside the function as error: $local_variable"
EXPLANATION

Here, in #!/bin/bash, ‘#!’ is called Shebang’ or ‘Hashbang. This script indicates the access of a declared local variable from both inside and outside a function and then displays the outputs employing the echo command.

➌ Then, press CTRL+S to save the file & press CTRL+X to exit.

➍ After that, use the command below to make the script executable:

chmod u+x local.sh
EXPLANATION
  • chmod: Changes the permission of the files and directories.
  • u+x: Adds the executable permission for the user.
  • local.sh: The file which you want to make executable.

Adding executable permission to the script

➎ Finally, run the script by the following command:

./local.sh

Output of local scope for variable

The above image depicts the local variable scope that you can access only inside the function.

Type 02: Global Scope for Variable in Bash

Global scope for variable defines a variable that you can access from any place of the current script or process except the sub-processes. Generally, global variables are declared outside a function but can be accessible from both inside and outside the function. These variables exist permanently throughout the lifespan of the current script and any section of the program can use the values of the variables. Here’s an example:

You can follow the Steps of Type 01, to save & make the script executable.

Script (global.sh) >

#!/bin/bash

#Defining a global variable
global_variable="I am a global variable"

function2() {
  #Accessing the global variable ‘global_variable’ inside the function
  echo "Global variable inside the function as error: $global_variable"
}
function2

#Accessing the global variable ‘global_variable’ outside the function
echo "Global variable outside the function: $global_variable"
EXPLANATION

The above script represents the access of a defined global variable from both inside and outside a function and then uses the echo command to display the outputs.

Now, run the script by the following command:

./global.sh

Output of global scope for variable

The above image depicts the global variable scope that you can access from inside the function as well as outside the function.

Unbound Variable – An Error!

Whenever you try to access or use any variable that is not declared or initialized yet, you will undoubtedly encounter an error called the ‘unbound variable’ error. This error occurs when the variable does not exist and Bash can not refer any value to the unassigned variable.

You can follow the Steps of Type 01, to save & make the script executable.

Script (unbound.sh) >

#!/bin/bash

#Attempting to use an undefined variable
echo "The variable is: $var"
EXPLANATION

The script above demonstrates an unbound variable error due to the undefined variable ‘var’ and displays the output using the echo command.

Now, run the script by the following command:

./unbound.sh

Output of an unbound variable error

The above image is an illustration of an unbound variable error that is the consequence of accessing an undefined variable.

2 Scenarios of How to Change Bash Variable Scope

In Bash, changing variable scopes is not a general and frequent task as it makes your code less obvious and leads to unintended variable conflicts. But if you have a justified reason for doing so, you can proceed with the variable scope conversion judiciously but make sure to document your scripts with clarity.

Anyway, the following section indicates two scenarios for changing scope from global to local and local to global. Let’s have a look!

Scenario 01: Changing Scope From Global to Local

This case is about changing the variable scope from global to local. To convert a global variable to a local variable, you need to use the ‘local’ keyword and declare the variable with the same name within the function. This local variable shadows the previous global variable inside the function and its scope remains limited to the function where the global variable maintains its value outside the function. This is known as the ‘variable shadowing’ concept. Here’s an example:

You can follow the Steps of Type 01, to save & make the script executable.

Script (change1.sh) >

#!/bin/bash

#Defining a global variable
global_var="Hello, Linux!"

function my_func() {
  #Changing the scope of 'global_var' to local
  local global_var="Hi, Ubuntu!"
  #Accessing 'global_var' inside the function
  echo "Local variable : global_var = $global_var"
}
my_func

#Accessing the global variable 'global_var'
echo "Global variable : global_var = $global_var"
EXPLANATION

This script first defines a global variable and then converts it to a local variable by using the ‘local’ keyword inside a function. Finally, it echoes the results from both inside and outside the function to see the difference.

Now, run the script by the following command:

./change1.sh

Output of changing scope from global to local

From the image, you can see the conversion of scope from global to local where the local variable within the function takes precedence over the global variable outside the function.

Scenario 02: Changing Scope From Local to Global in Bash

You can convert the scope from local to global by employing the ‘declare’ command with the ‘-g’ option within a function. It allows you to declare a global variable inside the function that is accessible from anywhere in the script.

You can follow the Steps of Type 01, to save & make the script executable.

Script (change2.sh) >

#!/bin/bash

function my_func() {
  local local_var="Hello, Linux!"
  #Changing the scope of 'local_var' to global
  declare -g global_var="$local_var"
}
my_func

#Accessing 'global_var' outside the function
echo "Global variable : global_var = $global_var"
EXPLANATION

Here, the script first defines a local variable inside a function using the ‘local’ keyword and then converts it to a global variable by using the ‘declare’ command with the ‘-g’ option inside the function. Finally, the script terminates by displaying the output using the echo command.

Now, run the script by the following command:

./change2.sh

Output of changing scope from local to global

From the image, you can see the conversion of scope from local to global where you can access the global variable even from outside the function.

Conclusion

To conclude, it’s recommended to employ the variable scopes properly to prevent unexpected conflicts within the bash scripts. Use local variables within functions to limit their scope and utilize global variables for cases when data needs to be shared across different sections of the program.

People Also Ask

Does Bash allow to make a global variable local within a function?

Yes, Bash allows making a global variable local within a function. To do so, use the ‘local’ keyword and declare the variable as a local variable within the function.

For how long does a local variable exist in Bash?

A local variable is only available for a limited lifetime in Bash. It exists only during the function’s execution.

Can I access global variables from within functions in Bash?

Yes, you can access global variables from within functions in Bash as they are accessible from anywhere in the script.

Are there any ways to create limited scope variables except local variables in Bash?

No, there are no default ways to create limited scope variables except local variables within a function in Bash. But if you want to create limited scope variables outside of the function for particular cases, you can use temporary files or create a ‘subshell’ using parentheses.

Related Articles


<< Go Back to Bash Variables | Bash Scripting Tutorial

Rate this post
Nadiba Rahman

Hello, This is Nadiba Rahman, currently working as a Linux Content Developer Executive at SOFTEKO. I have completed my graduation with a bachelor’s degree in Electronics & Telecommunication Engineering from Rajshahi University of Engineering & Technology (RUET).I am quite passionate about crafting. I really adore exploring and learning new things which always helps me to think transparently. And this curiosity led me to pursue knowledge about Linux. My goal is to portray Linux-based practical problems and share them with you. Read Full Bio

Leave a Comment