How to Declare Variable in Bash Scripts? [5 Practical Cases]

Like other programming languages, Bash scripting relies heavily on its variables. So understanding how to declare variable and create them in Bash is essential for effective script development. Unlike other programming languages, generally, the variable declaration is not necessary in the bash scripting. However, if needed, you can declare a variable with the “declare” command.  In this article, I will explore the syntax for declaring variables, discuss the associated options relevant to the “declare” command, and uncover some case examples to understand the practice of declaring the variable within the code. So let’s start.

Key Takeaways

  • Learning the basic syntax of variable declaration.
  • Having an idea of options used in variable declaration.
  • Learning the variable declaration for different data types.

Free Downloads

The “declare” Command in Bash Scripts

In Bash scripting, you can use the declare command to declare variables explicitly and set their attributes. The basic syntax of the “declare” command is:

declare [options] variable_name=value

Useful Options

Using options with the declare command provides explicit control and customization over the variable declaration. These options allow you to enforce specific data types, declare read-only variables, export variables to the environment, display variable attributes, etc.

Here are some commonly used options with the declare command:

Option Description
-i Declares an integer variable.
-a Declares an array variable.
-A Declares an associative array variable.
-f Declares a function.
-l Converts variable value to lowercase.
-u Converts variable value to uppercase.
-r Declares a read-only variable.
-x Declares an exportable variable.
-p Displays attributes and values of variables.
-g Declares a variable as global (available in function scopes).
-n Treats the variable as unset (without assigning a value).
-t Declares a variable as a trace option.
-x Declares a variable as automatically exported.

5 Cases to Declare Variables in Bash Script

In the following sections, I will give you five different cases to use options in variable declaration. Understanding and practicing those cases give you a better grasp of the variable declaration.

Case 01: Declare Variable Without an Option

When declaring variables without options, Bash treats them as strings by default. This allows for flexibility in storing and manipulating text-based data within scripts.

To declare a variable without an option, you can follow the approach given in the below script:

Steps to Follow >

❶ At first, launch an Ubuntu Terminal.

❷ Write the following command to open a file in Nano:

nano Var_declare_without_option.sh
EXPLANATION
  • nano: Opens a file in the Nano text editor.
  • Var_declare_without_option.sh: Name of the file.

❸ Copy the script mentioned below in your nano editor:

#!/bin/bash
#Declare a variable without a value
declare variable1

#Declaring variable without a option and value
declare -- variable2
#Create a variable with the value
declare variable3="Hello"

#Print the output of the variables
echo $variable1
echo $varibale2
echo $variable3
EXPLANATION

Here, #! /bin/bash: ‘#!’, is called shebang or hashbang. It indicates the interpreter to be used for executing the script, in this case, it’s bash. Next, the code declares three individual variables named variable1, variable2, and variable3. Since no values are assigned to variable1 and variable2, they are set as null or empty strings. By default, variables in Bash scripts are treated as strings unless specified otherwise. Later, the echo command is used to print the values stored in those three variables.

❹ Press CTRL+O and ENTER to save the file; then CTRL+X to exit.

❺ Use the following command to make the file executable:

chmod u+x Var_declare_without_option.sh
EXPLANATION
  • chmod: is used to change the permissions of files and directories.
  • u+x: Here, u refers to the “user” or the owner of the file and +x specifies the permission being added, in this case, the “execute” permission. When u+x is added to the file permissions, it grants the user (owner) of the file permission to execute (run) the file.
  • Var_declare_without_option.sh: Name of the script.

➏ Finally, run the script by the following command:

./Var_declare_without_option.sh

Output image of declaring variable without optionThe output simply gives the containing value for three variables, variable1, variable2, and variable3. Varibale1 and varibale2 return null output as those don’t contain any value whereas variable3 returns Hello as an output.

Case 02: Create Integer Variable With the “-i” Option

The option -i allows taking a variable as an integer form. For your understanding, here is a user case described below.

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

Script (Var_declare_with_i_option.sh) >

#!/bin/bash
#Declare an integer variable with -i option
declare -i var

#taking integer value from the user
read -p "Enter a Number:" var

#print the input value
echo "The given integer value is $var"
EXPLANATION

In this code, the shebang line #!/bin/bash specifies that the script should be executed using the Bash interpreter. Later, the var variable is declared as an integer variable. The read -p command is used to prompt the user to enter a value. Then the echo command will print the var value.

Now, run the script by using the following command:

./Var_declare_with_i_option.sh

Output image of declaring variable with i optionAs the user insert 4 as the data of var variable, the output message will be “The given integer value is 4”

Case 03: Declare and Create Arrays With the “-a” Option

For declaring array variable in bash scripting, the -a option with the declare command is used. The array variable provides a convenient way to work with collections of data.

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

Script (Var_declare_with_a_option.sh) >

#!/bin/bash
#Declare an index array variable with -i option
declare -a var_array

#taking the value of array from the user
read -p "Enter the array values: " var_array
echo "The Entered array values are:"

#Print the array values
for value in ${var_array[@]}
do
echo $value
done
EXPLANATION

In this code, the shebang line #!/bin/bash specifies that the script should be executed using the Bash interpreter. The line declare -a var_array declares a variable named var_array as an indexed array using the -a option. This means that var_array can hold multiple values as an array. The read -p command allows the user to give the array value. Later a for loop was incorporated to display each of the elements contained in the var_array.

Now, run the script using the following command:

./Var_declare_with_a_option.sh

Output image of declaring variable with a option declare variable bashHere, I insert some integer, float, and string values as an element of the var_array. The echo command then displays those given values 23 234 45 12 fan 2.45 with the help of a for loop.

Case 04: Declare Upper Case String With the “-u” Option

Apart from declaring different data types, you can use the -u option to make your string in uppercase form. Here is another case that has been described below.

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

Script (Var_declare_with_u_option.sh) >

#!/bin/bash
#Declare String variable with the Uppercase value
declare -u upstring
read -p "Enter your string Value: " upstring

#Print the variable
echo "The Uppercase form of the given String is $upstring"
EXPLANATION

In this code, the shebang line #!/bin/bash specifies that the script should be executed using the Bash interpreter. The line declare -u upstring declares a variable named upstring as a string with the uppercase value using the -u option. This means that the value of upstring will be converted to uppercase. The read -p command allows the user to give any string value. The echo command displays the given string in uppercase.

Now, run the script using the following command:

./Var_declare_with_u_option.sh

Output image of declaring variable with u optionIn this code, option -u turns Linuxsimply into LINUXSIMPLY and the output shows The uppercase form of the given String is LINUXSIMPLY.

Case 05: Declare and Create Read-Only Variable With the “-r” Option

In some cases, developers like you prefer to store some immutable value in their script to use it later. Those variables are known as readonly variables. The “-r” option is used to declare variable in bash and create a readonly variable. When a variable is marked as readonly, its value cannot be modified or reassigned throughout the script execution.

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

Script (Var_declare_with_i_option.sh)>

#!/bin/bash
# Declare and create a read-only variable
declare -r MY_VARIABLE="Hello, World!"

# Attempt to modify the value (will result in an error)
MY_VARIABLE="New value"

# Print the value of the read-only variable
echo "The given Read-Only variable is $MY_VARIABLE"
EXPLANATION

In this code, the shebang line #!/bin/bash specifies that the script should be executed using the Bash interpreter. Then, the code stores “Hello World” in MY_VARIABLE. Later the code attempts to modify the value of the readonly variable MY_VARIABLE by assigning it a new value, “New value“. However, since the variable is declared as readonly, this line will generate an error. Finally, the code displays the data stored in MY_VARIABLE with the echo command.

Now, run the script by using the following command:

./Var_declare_with_r_option.sh

Output image of declaring variable with r optionAs the image suggests, the first line displays an error since the corresponding script line tries to change the data of MY_VARIABLE. However, the output displays “The given Read-Only variable is Hello, World!”, as its initial value.

Conclusion

In conclusion, Declaring variables in Bash scripts is important because it allows you to store and manipulate data according to your need within your script. In this tutorial, I have discussed several ways to declare variable in bash scripts. However, there are much more cases for variable declaration. So don’t stop to explore more. If you have any queries related to this article, feel free to comment below.

People Also Ask

how to assign float to variable in bash?

In Bash, you cannot directly declare a variable with a specific data type, including float. Bash treats all variables as strings by default. However, you can work with float values by using external commands like bc or awk for arithmetic operations and calculations.

How do I declare a command in bash?

To declare a command in Bash, you simply write the command with option or no option and then assign variables with values. Use the equal (=) sign when assigning values to variables. Here’s a simple example:

my_command="echo Hello, World!"

In this case, a variable named my_command is declared, and the command echo Hello, World! is assigned to it. Later, you can execute the command by invoking the variable like $($my_command). This will execute the command stored in the variable my_command, which in this example would output: Hello, World!.

How do I assign a variable to a variable in bash?

To assign the value of one variable to another variable in Bash, you can use the syntax variable2=”$variable1″.

What is $$ in bash script?

In a Bash script, $$ is a special variable that represents the process ID (PID) of the currently running script or shell. It is a system-generated identifier assigned to each running process, including the script itself.

How to add value in bash?

To add values in Bash, you can use the arithmetic expansion syntax. result=$((value1 + value2)). Replace value1 and value2 with the actual numeric values you want to add. The result will be stored in the result variable.

Related Articles


<< Go Back to Variable Declaration and Assignment | Bash Variables | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux
Mohammad Shah Miran

Hey, I'm Mohammad Shah Miran, previously worked as a VBA and Excel Content Developer at SOFTEKO, and for now working as a Linux Content Developer Executive in LinuxSimply Project. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). As a part of my job, i communicate with Linux operating system, without letting the GUI to intervene and try to pass it to our audience.

Leave a Comment