Variables in Bash Function [Easy Reference]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

Variables defined within a Bash function may have different scopes. A variable declared in a function can only be available within that function. On the other hand, some variables are global and can be accessed both within and outside of a function. Furthermore, variables can vary in many ways. They could be a regular string-type variable or an array. They could be defined inside or outside of a function or even passed as an argument. The nuance of variables in a Bash function is the topic of today’s discussion.

Scope of Variables in Bash Function

By default, variables are global in Bash. However, a variable can be local within the context of function depending on the definition of the variable. Let’s talk more about the local and global scope of Bash variables:

A. Local Scope

A variable is local when it is visible only within a block of code. For instance, a local variable of a function can be accessed within the function only. To declare a local variable, supply the keyword local before the name of the variable:

#!/bin/bash

func(){
local num1=60 # set a local variable
echo "The number is: $num1"
}

func
echo "The number is: $num1"
EXPLANATION

num1 is a local variable of the func function as it is defined using the reserved word “local”. The echo command attempts to access the variable within the function and from outside of the function scope.

Local variable in bash functionOutput shows that the availability of the num1 variable is limited to the context of the “func“ function only. The variable is invisible outside of the function as the second echo command doesn’t show the value of the variable.

B. Global Scope

A variable in Bash is global unless it is defined by the reserved word “local”. Hence, by default variables are global no matter whether it is defined inside or outside of a function. So a global variable defined inside of a function can be accessed or changed outside of the function scope.

#!/bin/bash

func(){
num1=60
echo "The number is: $num1"
}

func
echo "The number is: $num1"
EXPLANATION

num1 is a global variable defined inside the function func. The echo command accesses the variable from inside the function and outside of the function scope.

Global variable in bash functionBoth echo statements retrieve the value of the variable num1 which is 60. The second echo command can access the value of the variable only because num1 is a global variable.

A Bash variable must be initialized before it is called. Referring to a variable that is not yet defined leads to an unintended outcome:

#!/bin/bash

func1 () {
echo "The number is: $num1"
num1=60
echo "The number is: $num1"
}

# Attempting to call the function
func1

Variable referencing in bash functionInitially, num1 is referenced before assigned a value, so it prints an empty string. After that, num1 is set to 60 so that the echo command can access the updated value.

Furthermore, a local variable within a function shadows a global variable of the same name. Look at the following example:

#!/bin/bash

num1=10  # Global variable

func2 () {
local num1=20  # Local variable with the same name as the global variable
echo "Value of number inside the function: $num1"
}

# Call the function
func2
EXPLANATION

The value of the global num1 is set to 10. Inside the function, the value of the local num1 variable is set to 20. Then an echo statement accesses the variable inside the function.

Shadowing global variable inside bash functionWhen executed the echo command of “func2“ referred to the local num1 variable. Therefore, if the name of a global variable is the same as the name of a local variable, then the local variable takes precedence over the global in its scope.

Global variables defined inside a function and written in a script are only available after the function call.

#!/bin/bash

func3 () {
num1=20
}

echo "The number is: $num1"
EXPLANATION

Global variable num1 is defined within the “func3“ function. The program tried to access the variable using the echo command without calling the function.

Availability of variable defined in bash functionAs expected attempting to access the variable num1 without calling the “func3“ function can’t retrieve the variable.

Nested Scoping of Variables in Bash Function

The visibility of variables depends on the sequence of function calls. So the scope of a local variable extends not only to the parent function but also to its subsequent child scopes:

#!/bin/bash

f1 ()
{
local num1=20
echo "Within function1 the number is: $num1"
f2
}
f2 ()
{
echo "Within function2 the number is: $num1"
}
f1
EXPLANATION

Here, num1 is set to 20 as a local variable in the scope of f1 function. Then f2 function is called within f1, creating a nested scope. This makes f2 a child scope for the variables of f1.

Within the f2 function, the echo command tries to access the local variable num1 that is defined in the f1 function.

Nested child scopes of bash function variablesAs you see, the num1 variable is available to the f2 function though it is defined as a local variable in f1.

How to Pass Variable as Argument in Bash Function

To pass variables as arguments to a Bash function simply refer to the variable name right after the function’s name when calling the function. The welcome function of the following script requires an argument for proper execution:

#!/bin/bash

user="Anita"
welcome () {
echo "Hello $1. Welcome to LinuxSimply"
}

welcome "$user"
EXPLANATION

Here, user variable is passed as an argument to the welcome function. The function utilizes the value of the variable when it uses the positional parameter $1 to refer to the argument.

Variables as argument in Bash functionThe program successfully prints a welcome message utilizing the argument “user”.

To supply multiple variables as arguments to a function place them one after one separated by a space. Look at the function below that takes multiple arguments:

#!/bin/bash

num1=5
num2=7
sum() {
result=$(( $1 + $2 ))
echo "Sum of the numbers: $result"
}

# Calling the function
sum $num1 $num2
EXPLANATION

Two variables $num1 and $num2 are supplied as arguments to the sum function. The function retrieves the value of the variables when calling the arguments using the positional parameters $1 and $2 respectively.

Multiple variables as argument in Bash functionUpon execution, the program successfully prints the summation of two variables num1 and num2.

Changing Scope of Local Variable to Global in Bash

To change the scope of a local variable to global use the declare command with -g option. It allows you to declare a global variable by referring to an already-defined local variable:

#!/bin/bash

my_func() {
local l_var="This is a variable."
#Changing the scope to global
declare -g g_var="$l_var"
}

my_func

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

Within “my_func”, the script defines a local variable l_var. Then it converts the local variable to a global one using declare -g. Finally, the script attempts to access the global variable from outside of the function

Converting a local variable to global in BashThe output shows that the local variable l-var is successfully converted into a global variable. Because when accessed from outside of the function the program can print the value of the variable.

Indirect Variable Referencing in Bash Function

Indirect referencing offers a tortuous mechanism of providing variables as arguments to a Bash function. $var_name directly refers to a particular variable. However, placing an exclamation before the name of the variable like- ${!var_name} indicates an indirect referencing.

#!/bin/bash

greet ()
{
echo "$1"
}

message=Hello
Hello=Goodbye

greet "$message"
greet "${!message}"
EXPLANATION

In this Bash script, a function called greet is defined. The simple function prints the first positional parameter using $1. The variable message is set to “Hello” and another variable named Hello is assigned the value “Goodbye.”

The function is then called twice. In the first call, the value of the variable message is passed as an argument.

In the second call, ${!message} is used to indirectly refer to the variable whose name is stored in the variable message.

Indirect variable referencing in Bash functionAs expected, ${!message} refers to the variable Hello. Hence the function prints “Goodbye” or the value of the variable “Hello” in the second call.

Conclusion

In conclusion, variables in a Bash function can be of two types- local or global. One can easily convert a local variable to a global and vice versa. Hope this article helps you to understand the scope of local and global variables in Bash. I believe from now on you can easily manipulate variables of Bash function.

People Also Ask

How to create a local variable in bash function?

To create a local variable in bash function use the reserved word “local”. Local variables are only accessible within the scope they are declared in. In the following script, the str variable is defined as local:

#!/bin/bash

my_function() {
local str="Welcome to Linux World"
echo "$str"
}
# Call the function
my_function

How to avoid positional arguments in Bash?

There is absolutely no way to avoid positional arguments. However, if you are bored with the syntax of positional parameters you can store the arguments in global variables. But make sure you assign the variables before the function call.

Can I define a local variable outside of a Bash function?

No. If you try to define a local variable outside of a Bash function, it will raise an error. The use of the keyword “local” is valid only within the context of a function.

How can I get all the variables in Bash?

You can get all the variables using the command typeset -p. If you are searching for a specific variable, use the grep command to find it from the output of “typeset -p“.

What are the best practices for naming global variables in Bash?

When naming global variables, it’s better to use clear and descriptive names that convey their purpose. I would not suggest using uppercase letters for the naming of global variables as it may conflict with the environment variables.

Do positional parameters fall in the global scope?

No. Positional parameters are always local to a Bash function. Therefore, any manipulation of positional parameters also falls within the function scope. However, you can take the value of a positional parameter and save it to a global variable.

What is the role of local variables in recursive functions?

The role of local variables in recursive functions is crucial. They are useful to write efficient recursive functions. As recursive functions use values that change with each function call, it’s necessary to store those values in local variables.

Related Articles


<< Go Back to Bash Functions | Bash Scripting Tutorial

Rate this post
Md Zahidul Islam Laku

Hey, I'm Zahidul Islam Laku currently working as a Linux Content Developer Executive at SOFTEKO. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). I write articles on a variety of tech topics including Linux. Learning and writing on Linux is nothing but fun as it gives me more power on my machine. What can be more efficient than interacting with the Operating System without Graphical User Interface! Read Full Bio

1 thought on “Variables in Bash Function [Easy Reference]”

Leave a Comment