JIYIK CN >

Current Location:Home > Learning > OPERATING SYSTEM >

Bash variable scope

Author:JIYIK Last Updated:2025/03/23 Views:

In this article, we will learn about bash variable scope in Linux. We also learned how to declare variables in bash scripts in Linux operating system.

Furthermore, we will see different types of variables and how to access local and global variables in bash scripts using Linux operating system. Let us start with the concept of variables used in Linux.


Bash variable scope in Linux

A variable is a temporary storage space for various data types handled in any programming language. A variable is usually associated with two separate entities: the data type and its value.

The data type describes the data stored in the variable, whereas the value represents the data itself. While declaring a variable in Bash programming, we do not need to explicitly specify the data type.

This is because the programming language itself detects the data type. For example, in bash, if we assign a number to a variable, it is immediately treated as an integer.


How to declare variables in Bash

In bash, we can declare a variable with any name using the equal sign "=" and the value we want to assign. Here are some rules we can follow when declaring variables in bash:

  • Uppercase and lowercase letters, numbers, underscores, and decimals are all acceptable characters for variable names.
  • It is recommended to use uppercase letters for variable names in Bash scripts.
  • Do not put spaces around the equal sign "=".
  • All predefined keywords are restricted, such as if, else, local, etc.

Following is an example of declaring a String variable in bash. We open the terminal and declare the variable. Don't forget that while declaring the variable, we are not allowed to put any spaces around the equal sign ('=').

$ _name=abid

We use echoto get the output of the variable.

$ echo $_name

Output:

abid

Declare an integer variable in bash.

$ _age=24

Similarly, using echo, we can also get the output of this variable.

$ echo $_age

Output:

24

Variable scope in Bash

The scope of Bash variables can be local or global, just like in any other programming language. It does not matter where they are declared in our Bash script.

By default, all variables in bash have global scope. This means that the variable can be used inside any function in the bash script, even if it is defined in the middle of the script.

In other words, we might argue that in bash we don't always have to declare a variable at the beginning of a script to make its scope global.

Furthermore, if we want the scope of that variable to be limited to a specific function, we must explicitly use the local keyword when declaring a variable in bash, which means that no other functions in that script or anywhere else can access it.

This will ensure that the scope of the variable is limited to the function in which it is defined.


Variable Types

There are three main types of variable scopes we need to know about.

  1. Local variables
  2. Global variables
  3. Environment variables

Accessing local variables in Bash

We can access local variables only within the code block they are declared in. For example, if we declare a variable inside a Bash script, we will not be able to access it outside the code.

Sample code:

#!/bin/bash
echo "Learning the scope of local and global variables."

function_localVar(){
    echo "Within the function function_localVar"
    echo "Assign a variable with local keyword to a variable name: varLocal"
    local varLocal=27
    echo "Assign a variable without local keyword to a variable name: varLocal_wo"
    varLocal_wo=9
    echo "Printing within the function."
    echo "Value assigned to one with local keyword varLocal = $varLocal and without local keyword varLocal_wo = $varLocal_wo"
    echo "Exiting function_localVar"
}

glob_var=91
echo "Start of the code!"
echo "Global Variable = $glob_var"
echo "Local variable before calling function to one with local keyword varLocal = ** $varLocal ** and without local keyword varLocal_wo = ** $varLocal_wo **"
echo "Calling the function."

function_localVar

echo "Printing outside the function."
echo "Value assigned to one with local keyword varLocal = $varLocal and without local keyword varLocal_wo = $varLocal_wo"

Output:

Learning the scope of local and global variables.
Start of the code!
Global Variable = 91
Local variable before calling function to one with local keyword varLocal = **  ** and without local keyword varLocal_wo = **  **
Calling the function.
Within the function function_localVar
Assign a variable with local keyword to a variable name: varLocal
Assign a variable without local keyword to a variable name: varLocal_wo
Printing within the function.
Value assigned to one with local keyword varLocal = 27 and without local keyword varLocal_wo = 9
Exiting function_localVar
Printing outside the function.
Value assigned to one with local keyword varLocal = and without local keyword varLocal_wo = 9

Bash variable scope - local variables

From the following code, it is clear that, may be the local keyword sets the scope to local, even when the variable is read outside the function defined as local, it returns null.

Accessing Global Scope Variables in Bash

We can access global variables throughout the bash script. The following example helps us understand how global variable scope works in bash.

Sample code:

var1='Abid'
var2='Ali'
my_function () {
    local var1='Micheal'
    var2='Den'
    echo "Inside function: var1: $var1, var2: $var2"
}
echo "Before executing the function: var1: $var1, var2: $var2"
my_function
echo "After executing the function: var1: $var1, var2: $var2"

Output:

Before executing the function: var1: Abid, var2: Ali
Inside function: var1: Micheal, var2: Den
After executing the function: var1: Abid, var2: Den

Bash variable scope - global variables

The results of the above code lead us to the following conclusions:

  • Whenever you set a local variable in function scope with the same name as an existing global variable, the local variable will take precedence.
  • It is indeed possible to make changes to global variables from within a function.

Environment variables

Environment variables (ENV) essentially specify how the environment works. In bash, environment variables can have global or local scope.

We can access the globally scoped ENV generated in the terminal from anywhere in the terminal environment. Because it runs in the context of the terminal, it can be used in any script, program or process.

Any application or process executed in the terminal cannot access the local scope ENV specified there. Only the terminal in which we define the variable can access it.

Setting Environment Variables

As an environment variable at global scope:

$ export COUNTRY=USA
# 或者
$ set NAME=Abid

As a locally scoped environment variable:

$ NAME=Abid

Now, the point is how to display environment variables. We can use to echodisplay environment variables like normal variables.

$ echo $COUNTRY 

Output:

USA

The output of this command will be the value we assigned to this variable COUNTRY, which is USA.

Display all environment variables

We can display all ENV using three different commands.

  • Only used to display all global environment variables
    $ printenv
    
  • We use this command to display local and global environment variables
    $ set
    
  • Used to display all global environment variables
    $ env
    

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Hosting Docker Internal in Linux

Publish Date:2025/03/23 Views:143 Category:OPERATING SYSTEM

Docker allows developers to efficiently build, test, and deploy applications by packaging them in standardized units called containers. When working with Docker containers, you may encounter scenarios where you need to connect a container t

Setting the working directory in Docker

Publish Date:2025/03/23 Views:198 Category:OPERATING SYSTEM

If present, the working directory of a process in Compute is a directory in a linked hierarchical file system that is dynamic for each process. In Docker, we can set our working directory by editing the Dockerfile and adding the key WORKDIR

How to get IP address in CentOS

Publish Date:2025/03/23 Views:108 Category:OPERATING SYSTEM

This short article is a brief introduction to CentOS followed by a brief discussion on how we can get the server IP address in CentOS using the Command Line Interface (CLI). This article will discuss some of the commands and their usage for

Updating YUM in Linux

Publish Date:2025/03/23 Views:148 Category:OPERATING SYSTEM

This article will teach us how to update YUM in Linux and how to install, update, remove, find and manage packages on a Linux system. We have also seen the difference yum update between and in Linux yum upgrade . yum update command in Linux

Installing Deb Files in Linux

Publish Date:2025/03/23 Views:93 Category:OPERATING SYSTEM

In this Linux article, we will learn how to install .deb (Debian Package) files on Linux systems. We will also see how to remove .deb files after installation. More importantly, we will learn different ways to install .deb files on Linux sy

lsof Command in Linux

Publish Date:2025/03/23 Views:100 Category:OPERATING SYSTEM

In this Linux article, we will learn about lsof command in Linux operating system. We will see how to use this command for different purposes in Linux. We use lsof the lsof command to verify the ports in use on the Linux operating system. U

ps aux command in Linux

Publish Date:2025/03/23 Views:57 Category:OPERATING SYSTEM

If you are using Linux and are looking for a tool that can monitor all the processes running on your system, then you should use the command ps aux. This command will show you an overview of all running processes. It is very useful for trou

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial