Types of Variables in Bash

As Bash is a dynamically typed shell, it understands many different types of variables. So, you don’t have to bother about what kind of variables you need to assign. Having a compact knowledge of Bash variable types is enough to choose the perfect data structure for your operations accordingly. In this article, I’m going to share the basic context of variable types in Bash. Let’s dive into it.

Key Takeaways

  • Learning about different variable types in Bash.
  • Observing several examples of Bash variable types.

Free Downloads

What Are Bash Variables?

Bash variables are temporary storage where you can store various data types like integers, strings, arrays, etc. They do not need any evident declaration always. In fact, these variables are the essential parts that serve users by being referenced and manipulated in Bash programming.

Types of Bash Variables

There are two types of variables in Bash. They are described below:

  • System-defined Variables: System-defined variables are the default and pre-defined variables in Bash. Basically, you can define them in capital letters (UPPER_CASE). These are actually the built-in variables in the Linux Bash shell that are accessible whenever you open a new session.
  • User-defined Variables: User-defined variables specify the variables that you create and manipulate as a user. These variables are not predefined by the Bash shell. So, there are no certain rules to write these. You can define them in both UPPER_CASE or LOWER_CASE. These user-defined variables are so versatile to use that you can smoothly manage data as per your preferences during the execution.

2 Cases for Checking Variable Types in Bash

You can check the type of variables you have inserted within your script in the following two manners:

Case 1: Checking Variable Type Using “declare” Command

Using the built-in declare command, you can easily identify the variable types, values, attributes, etc. Here’s the step-by-step procedure for checking the variable type using the “declare” command:

Steps to Follow >

➊ Open your Ubuntu Terminal.

➋ To open a script in the nano text editor, write the command below:

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

Opening file in Nano editor

➌ Hereafter, write the following script inside the editor:

Script (declare.sh) >

#!/bin/bash

#Assigning variables
website="LinuxSimply"
number=25
array=(1 3 5 7 9)

#Using 'declare' to check variable types
declare -p website
declare -p number
declare -p array
EXPLANATION

Here, ‘#!’ is known as ‘Shebang’ or ‘Hashbang’ in #!/bin/bash. Then, in the lines ‘declare -p website’, ‘declare -p number’, and ‘declare -p array’, the “declare” command displays information about the assigned variables ‘website’, ‘number’, and ‘array’.

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

Adding executable permission to the script

➏ Finally, run the script by the following command:

./declare.sh

Output showing the type of the variable using the 'declare' command

From the image, you can see the values of the assigned variables in the code. Thus, you can identify what types of variables are there.

Case 2: Checking Variable Type Using Conditional Statements

Another way of checking a variable’s type (whether it’s a string, an integer, or an array) in Bash is using conditional statements. Here’s an example of such a scheme:

You can follow the steps of Case 01, to save & make the script executable.

Script (conditional.sh) >

#!/bin/bash

variable1="2023"
variable2="LinuxSimply"

var_integer() {

  if [[ "$1" =~ ^[0-9]+$ ]]; then

    echo "Variable '$1' is an Integer."
  else
    echo "Variable '$1' is a String."
  fi
}

var_integer "$variable1"
var_integer "$variable2"
EXPLANATION

The line ‘if [[ “$1” =~ ^[0-9]+$ ]]; then’ checks if the values inserted to the variables and passed to the ‘var_integer’ function match with ‘^[0-9]+$’. Here, ‘^[0-9]+$’ checks if any string contains only digits (0-9). If the regular expression ‘^[0-9]+$’ matches, and the if condition becomes true the echo command prints the line “Variable ‘$1’ is an Integer.”, otherwise, it moves to the else block and the echo command prints the line “Variable ‘$1’ is a String.”.

Now, run the script by the following command:

./conditional.sh

Output showing the type of the variable using the conditional statement

The above image dictates the types of values that I have assigned to the variables.

Best Practices for Using Various Types of Variables in Bash

Using Bash variables properly can make your script more impactful. Here are some best practices that you need to follow while using different types of variables in Bash:

  • Purpose of the Variables: Comment on the purpose of each variable you are going to use. This will be helpful for others and for your future self too to get a clear overview of the variables and code.
  • Relevant Variable Names: Try to use relevant and meaningful names for your variables. This will make your code more understandable to the readers.
  • Double-quote Variables: Double-quote variable expansions during referencing like “$variable” to avoid word splitting.
  • Lowercase Variable Names: Be cautious while naming a variable and try to use lowercase letters for this to avoid overwriting the built-in variables in Bash.
  • Variable Declaration with ‘local’: During variable declaration within a function, try to use ‘local’ to limit the variables’ activities within the function.
  • Define Variables: To avoid unexpected errors or bugs, always define variables with default values before using them.
  • Test Empty Variables: Before further use, apply conditional statements to check if the assigned variables are null. You can use the ‘-n’ or ‘-z’ test in this case.
  • Check Exit Status: Check the exit status to handle the Bash error and implement a proper control flow.
  • Clear Variables: When the variables are no longer needed, unset them and clean up the memory to avoid clutter.

Conclusion

So far, you have got that Bash variables do not have any fixed type, i.e., they can hold different data types based on their assigned values. And this is one of the best things you’ll find in Bash it supports any kind of assigned variables and helps in manipulating data for interactive shell sessions.

People Also Ask

Can I change the variable type in Bash?
Yes, you can change the variable type by assigning different types of values.

Can Bash variables hold complex data structures?
Of course, Bash variables can hold complex data structures like arrays, associative arrays, etc.

Are all Default Bash variables global?
Yes, every default variable created in Bash is global and accessible anywhere in the script.

Is there any specific data type of a variable in Bash?
No, there is no specific data type of a variable in Bash. You can change their types by appending different values.

Does Bash support floating-point variables?
No, by default Bash doesn’t support floating-point variables. You have to use commands like ‘bc’ to employ floating-point variables in Bash.

Related Articles


<< Go Back to Bash Variables | Bash Scripting Tutorial

Rate this post
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