How Unbound Variable Error Occurs in Bash [Cases & Solutions]

There may be a situation when you want to use a variable, but it’s not declared, assigned or initialized. In this effort, Bash raises an error alert called an ‘unbound variable error’ as it maintains a precise variable handling format. In this article, you’ll get to know different aspects of unbound variable errors in Bash that can help you make reliable shell scripts. So, let’s explore!

Key Takeaways

  • Learning about the unbound variable in Bash.
  • Exploring how to avoid unbound variable error.

Free Downloads

3 Cases of How Unbound Variable Error Occurs in Bash

In Bash scripting, an Unbound variable error generally occurs not only for undefined variables but also for uninitialized variables. In the following section, you will see three different examples of how unbound variable error occurs for both global and local variables:

Case 1: Accessing an Undefined Global Variable in Bash

If you ever try to access an undefined global variable, you will encounter an unbound variable error. Here’s such an example:

Steps to Follow >

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

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

Opening the file in Nano text editor

➋ Now, write the following script inside the editor:

Script (global.sh) >

#!/bin/bash

#Trying to use an undefined global variable
echo "The value of undefined_variable is: $undefined_variable"
EXPLANATION

Here, in #!/bin/bash, ‘#!’ is called Shebang’ or ‘Hashbang. This script indicates the unbound variable error caused while accessing the undefined global variable.

➌ 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 global.sh
EXPLANATION
  • chmod: Changes the permission of the files and directories.
  • u+x: Adds the executable permission for the user.
  • global.sh: The file which you want to make executable.

Adding executable permission to the script

➎ Finally, run the script by the following command:

./global.sh

An 'unbound variable' error occurs due to undefined global variable

From the image, you can see that an unbound variable error occurs because of accessing an undefined global variable ‘undefined_variable’.

Case 2: Accessing an Undefined Local Variable Within a Function in Bash

When attempting to access a local variable inside a function that is not declared yet, it would result in an ‘unbound variable’ error for sure. You can see the following example as a demo.

You can follow the Steps of Case 1, to save & make the script executable.

Script (local.sh) >

#!/bin/bash

function my_func() {
#Trying to use an undefined local variable
echo "The value of local_variable is: $local_variable"
}
my_func
EXPLANATION

The script finds an unbound variable error while accessing the undefined local variable inside a function.

Now, run the script by the following command:

./local.sh

An 'unbound variable' error occurs due to undefined local variable

From the image, you can see that an unbound variable error occurs because of accessing an undefined local variable ‘local_variable’.

Case 3: Accessing a Declared but Not Uninitialized Variable in Bash

It’s not necessary that a variable must be undefined to create an unbound variable error. Accessing a variable that is already declared but not initialized may also cause this error. Here’s an example of an unbound variable error due to an uninitialized variable.

You can follow the Steps of Case 1, to save & make the script executable.

Script (uninitialized.sh) >

#!/bin/bash

#Defining a variable
uninitialized=""

#Trying to use an uninitialized variable
echo "The uninitialized_variable is: $uninitialized"
EXPLANATION

The above script specifies an unbound variable error that occurred due to a declared but uninitialized variable.

Now, run the script by the following command:

./uninitialized.sh

An 'unbound variable' error occurs due to uninitialized variable

In the above image, you can see an unbound variable error that occurs during the access of a declared but uninitialized variable ‘uninitialized’.

Best Practices to Prevent Unbound Variable Errors in Bash

If you want to minimize the risk of unbound variable errors in your script, you must define and initialize all the variables. Otherwise, it will cause an explicit error within the script. Also, you can either check a variable’s existence before accessing it or set a default value to the variable or enable a ‘nounset’ option to handle these issues. Here, the following section illustrates some best practices you should follow to prevent unbound variable errors in Bash:

A. Defining and Initializing Variables

Always declare and initialize variables before attempting to access and use them. In case of global variables, you can declare them at the start of your script and for local variables, you can use ‘local’ within functions to declare and initialize them. Let’s have a look at the following instance.

You can follow the Steps of Case 1, to save & make the script executable.

Script (define.sh) >

#!/bin/bash

#Defining and initializing a global variable
global="A global variable"

function my_func() {
#Defining and initializing a local variable
local local_variable="A local variable"
echo "Variable inside the function: $local_variable"
}
my_func

echo "Variable outside the function: $global"
EXPLANATION

This script demonstrates a clear declaration and initialization of a global variable ‘global’ and a local variable ‘local_variable’. Finally, the script terminates by displaying the outputs using the echo commands.

Now, run the script by the following command:

./define.sh

Defining and initializing global and local variables to prevent unbound variable error

The above image depicts that if any global or local variables are defined or initialized before, then no unbound variable error can affect your scripts.

B. Checking Variable Existence Using Conditionals

You can use the ‘if…else’ conditional statement to verify whether a variable exists and contains any values before accessing it. For instance:

You can follow the Steps of Case 1, to save & make the script executable.

Script (existence.sh) >

#!/bin/bash

#Checking if the variable exists
if [ -n "$var" ]; then
echo "The variable exists: $var"
else
echo "The variable doesn’t exist."
fi
EXPLANATION

The above script checks if there is any existent variable called ‘var’ by using the ‘if..else’ conditional and displays the result using the echo command.

Now, run the script by the following command:

./existence.sh

Checking if variable exists using 'if' conditional to prevent unbound variable error

The above image indicates the prechecking of a variable’s existence. First, ensure that the specific variable exists and then proceed to access it to avoid the unbound variable error in your scripts.

C. Assigning Default Values in Bash Script

Another way to handle the unbound variable errors in the script is to use default values for a variable. When a variable is not potentially defined or initialized or empty, you can use the syntax ‘${variable:-default_value}’ and assign any type of default value to the variable. Then, instead of showing errors, it provides the default fallback values you assigned to the variable. Let’s see an example.

You can follow the Steps of Case 1, to save & make the script executable.

Script (default.sh) >

#!/bin/bash

#Using default value to access variable
variable="${variable:-default_value}"

echo "The variable is: $variable"
EXPLANATION

Here, the script assigns a default value to a variable to avoid unbound variable error and then echoes the output availing the echo command.

Now, run the script by the following command:

./default.sh

Using default value to access a variable to prevent unbound variable error

From the above image, you can see that by assigning a default value in an undefined or empty variable, you can easily handle the unbound variable error.

D. Enabling the “nounset” Option Using the “set -u” Command

There is one more option that is kind of optional but will help you point out unbound variable issues in your script. And that is the ‘nounset’ option. When you use the ‘set -u’ command at the beginning of the script, Bash enables the ‘nounset’ option, terminates your script and treats the undefined variables as errors. This approach is definitely helpful for identifying and fixing unbound variable errors gracefully during script development.

You can follow the Steps of Case 1, to save & make the script executable.

Script (optional.sh) >

#!/bin/bash

#Enabling 'nounset' option to identify unbound variable errors
set -u

echo "The variable is: $variable"
EXPLANATION

Here, the script uses the ‘set -u’ command judiciously to enable the ‘nounset’ option, identify the unbound variable error and stop the execution. At last, it employs the echo command to display the error message.

Now, run the script by the following command:

./optional.sh

Enabling the 'nounset' option using the 'set -u' command at the beginning of the script to prevent unbound variable error

The above snapshot is a clear indication of an unbound variable error that dictates that by using the ‘set -u’ command you can easily identify and fix the issues during Bash scripting.

Conclusion

So far, you have understood why unbound variable error occurs and what to do to prevent this issue. Wrapping up, if you understand the crucial steps of unbound variable errors perspicuously, these will help you address and fix all the potential issues and write maintainable Bash scripts.

People Also Ask

Can I disable the ‘nounset’ option in Bash?

Yes, you can disable the ‘nounset’ option by using the ‘set +u’ command in Bash.

Are there any risks while disabling the 'nounset' option in Bash scripts?

Yes, If you use any undefined variables, then disabling the ‘nounset’ option can lead to unintended potential issues in Bash scripts.

How to exit the script when encountered an unbound variable in Bash?

Use the command ‘set -u’ and enable the ‘nounset’ option. This will automatically treat the unbound variables as errors and take you out of the script.

Does Bash allow to customize the error messages for unbound variable errors?

No, Bash doesn’t allow direct customization of error messages for unbound variable errors, but you can redirect the output of the standard error in a custom log file to handle the errors according to your needs.

Related Articles


<< Go Back to Variable Scopes in Bash | Bash Variables | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
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