How to make a variable global?

QuestionsQuestions4 SkillsProShell FunctionsOct, 10 2025
0102

To make a variable global in a shell script, you can use the export command. This allows the variable to be accessible not only within the script but also in any child processes or subshells that are spawned from it.

Here’s how you can do it:

#!/bin/bash

# Declare a global variable
export my_global_var="I am global"

# Function to demonstrate access to the global variable
my_function() {
    echo $my_global_var  # This will print "I am global"
}

# Call the function
my_function

# Accessing the global variable outside the function
echo $my_global_var  # This will also print "I am global"

In this example, my_global_var is declared with export, making it a global variable that can be accessed both inside the function my_function and outside of it in the script.

0 Comments

no data
Be the first to share your comment!