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
- 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.
➋ 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"
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
- 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.
➎ Finally, run the script by the following command:
./global.sh
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.
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
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
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.
Script (uninitialized.sh) >
#!/bin/bash
#Defining a variable
uninitialized=""
#Trying to use an uninitialized variable
echo "The uninitialized_variable is: $uninitialized"
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
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.
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"
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
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:
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
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
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.
Script (default.sh) >
#!/bin/bash
#Using default value to access variable
variable="${variable:-default_value}"
echo "The variable is: $variable"
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
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.
Script (optional.sh) >
#!/bin/bash
#Enabling 'nounset' option to identify unbound variable errors
set -u
echo "The variable is: $variable"
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
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
Related Articles
- Insights to Local Variable in Bash [4 Practical Examples]
- A Total Guide on Global Variable in Bash [3 Examples]
<< Go Back to Variable Scopes in Bash | Bash Variables | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners