Variable Declaration and Assignment

In programming, a variable serves as a placeholder for an unknown value, enabling the user to store the different data and access them whenever needed. During compilation or interpretation, the symbolic names of variables are replaced with their corresponding data locations. This article will mainly focus on the variable declaration and assignment in a Bash Script. So, let’s start.

Key Takeaways

  • Getting familiar with Bash Variables.
  • Learning to declare and assign variables.

Free Downloads

Factors of Variable Declaration and Assignment

There are multiple factors to be followed to declare a variable and assign data to it. Here I have listed the factors below to understand the process. Check it out.

1. Choosing Appropriate Variable Name

When choosing appropriate variable names for declaration and assignment, it’s essential to follow some guidelines to ensure clarity and readability and to avoid conflicts with other system variables. Here some common guidelines to be followed are listed below:

  • Using descriptive names: Using descriptive names in variable naming conventions involves choosing meaningful and expressive names for variables in your code. This practice improves code readability and makes it easier to grasp the purpose of the code at a glance.
  • Using lowercase letters: It is a good practice to begin variable names with a lowercase letter. This convention is not enforced by the bash language itself, but it is a widely followed practice to improve code readability and maintain consistency. For example name, age, count, etc.
  • Separating words with underscores: Using underscores to separate words in variable names enhances code readability. For example first_name, num_students, etc.
  • Avoid starting with numbers: Variable names should not begin with a number. For instance, 1var is not a valid variable
  • Avoiding special characters: Avoid using special characters, whitespace, or punctuation marks, as they can cause syntax errors or introduce unexpected behavior. For instance, using any special character such as @, $, or # anywhere while declaring a variable is not legal.

2. Declaring the Variable in the Bash Script

In Bash, declaring variables and assigning values to them can be done for different data types by using different options along with the declare command. However, you can also declare and assign the variable value without explicitly specifying the type.

3. Assigning the Value to the Variable

When declaring variables for numeric values, simply assign the desired number directly, as in age=30 for an integer or price=12.99 for a floatingpoint value. For strings, enclose the text in single or double quotes, such as name=’John‘ or city=”New York“. Booleans can be represented using 0 and 1, where 0 indicates false and 1 represents true, like is_valid=1.

Note: In Bash scripting, single quotes (‘ ‘) and double quotes (” “) are used to define strings, but they behave differently in certain situations. For instance, in the case of double quotes, if you have a variable $name, it will be replaced with its value inside the double-quoted string. Whereas variables within single quotes are treated literally as normal strings. They won’t be expanded, and the variable names will be included as-is in the string.

Arrays are declared by assigning a sequence of values enclosed in parentheses to a variable, e.g., fruits=(“apple” “banana” “orange”). To create associative arrays (key-value pairs), use the declare -A command followed by assigning the elements, like declare -A ages=([“John”]=30 [“Jane”]=25).

4 Practical Cases of Declaring and Assigning Bash Variable

In this section, I have demonstrated some sample Bash scripts that will help you understand the basic concept of variable declaration and assignment in Bash script. So let’s get into it.

Case 01: Basic Variable Assignment in Bash Script

In my first case, I have shown a basic variable assignment with its output. Here, I have taken a string and an integer variable to show the basic variable assignment mechanism. Follow the given steps to accomplish the task.

Steps to Follow >

❶ At first, launch an Ubuntu terminal.

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

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

❸ Copy the script mentioned below:

#!/bin/bash
# Variable Declaration and Assignment
name="John"
age=30

# Printing the variables
echo "Name: $name"
echo "Age: $age"
EXPLANATION

The script starts with the shebang line (#!/bin/bash), specifying that the script should be executed using the Bash shell. Next, two variables are declared and assigned values using the format variable_name=value. The first variable is name, and it is assigned the string value “John.” The second variable is age, assigned the numeric value 30. The script then uses the echo command to print the values of the variables.

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

❺ Use the following command to make the file executable:

chmod u+x basic_var.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) permission to execute (run) the file.
  • basic_var.sh: File name to which the permissions are being applied.

❻ Run the script by the following command:

./basic_var.sh

Basic Variable Assignment in Bash ScriptUpon executing the script, the output displays the content of the variables: Name: John and Age: 30.

Case 02: Input From User and Variable Assignment

In Bash, you can take input from the user and store it in variables using the read command. To do so use the following script:

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

Script (user_var.sh) >

#!/bin/bash
# Prompt the user for input
read -p "Enter your name: " name
read -p "Enter your age: " age

# Printing the variables
echo "Name: $name"
echo "Age: $age"
EXPLANATION

The script starts with the shebang line (#!/bin/bash) to specify that the Bash shell should be used for executing the script. The read command is then used twice, each with the -p option, to prompt the user for input. Both the name and age variables take the name and age of the user and store them in the name and age variable with the help of the read command. Then the script uses the echo command to print the values of the variable’s name and age, respectively. The $name and $age syntax are used to access the values stored in the variables and display them in the output.

Now, run the following command into your terminal to execute the bash file.

./user_var.sh

Input from User and Variable AssignmentWhen you run the script, it will ask you to enter your name and age. Upon providing the input Jhon and 30, the script prints Name: John and Age: 30 in the terminal.

Case 03: Variable Assignment Using Positional Parameters

In Bash, you can assign values to variables using positional parameters. Positional parameters are special variables that hold arguments passed to the script when it is executed. They are referenced by their position, starting from $0 for the script name, $1 for the first argument, $2 for the second argument, and so on. To do the same use the below script.

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

Script (var_command_line.sh) >

#!/bin/bash
# Prompt the user for input
name=$1
age=$2

# Printing the variables
echo "Name: $name"
echo "Age: $age"
EXPLANATION

The script starts with the shebang line (#!/bin/bash) to specify that the Bash shell should be used for executing the script. The script uses the special variables $1 and $2, which represent the first and second commandline arguments, respectively, and assigns their values to the name and age variables. The $name and $age syntax are used to access the values stored in the variables and display them using the echo command.

Now, run the following command into your terminal to execute the script.

./var_command_line.sh John 30

Variable Assignment Using Positional Parameters

Upon execution of the Bash file, the script takes two command-line arguments, John and 30, and returns the output Name: John and Age: 30 in the command line.

Case 04:  Environment Variables and Variable Scope

In Bash script, Environment Variables are another type of variable. Those variables are available in the current session and its child processes once you export your own variable in the environment. However, you can access those and scope it to a function. Here’s a sample Bash script code of environment variables and variable scope describing the concept.

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

Script (var_scope.sh) >

#!/bin/bash
# Environment variable assignment
export MY_VARIABLE="Hello, World!"

# Function with a local variable

my_function() {
  local local_var="I am a local variable"
  echo "Function Output: $local_var"
}

# Printing the environment variable and calling the function
echo "Environment Variable: $MY_VARIABLE"
my_function
EXPLANATION

The script starts with the shebang line (#!/bin/bash) to specify that the Bash shell should be used for executing the script. Then, an environment variable named MY_VARIABLE is assigned the value “Hello, World!” using the export command. The script also defines a Bash function called my_function. Inside this function, a local variable named local_var is declared using the local keyword. After defining the function, the script proceeds to print the value of the environment variable MY_VARIABLE, which is accessible throughout the script. Upon calling the my_function, it prints the value of the local variable local_var, demonstrating its local scope.

Finally, run the following command into your terminal to execute the bash file.

./var_scope.sh

Environment Variables and Variable Scope

Upon printing the My_VARIABLE and calling the my_function, the code returns “Environment Variable: Hello, World” and “I am a local variable” respectively.

Conclusion

In conclusion, variable declaration and assignment is a very straightforward process and does not take any extra effort to declare the variable first, just like the Python programming language. In this article, I have tried to give you a guideline on how to declare and assign variables in a Bash Scripts. I have also provided some practical cases related to this topic. However, if you have any questions or queries regarding this article, feel free to comment below. I will get back to you soon. Thank You!

People Also Ask

What is variable declaration and assignment?
Variable declaration is the act of introducing a new variable to the program by specifying its name and type. As far as the Bash Script is concerned, the variable type does not need to declare explicitly.
What is used to assign a variable?
The equals sign (=) is for variable assignment in programming, like x = 5; where the variable x is assigned the value 5.
What is the difference between assignment statement and variable?
The assignment statement is a programming construct used to give a value to a variable. It involves using the equal sign “=” to assign a specific value or expression to a variable. On the other hand, a variable is a named storage location in the computer’s memory that holds a value. It acts as a placeholder for data and can be referenced by its name throughout the program.
How do you declare and assign variables?
In Bash, you can declare and assign variables in a single line without explicitly specifying the data type. For example, to declare and assign the variable name with the value “John” you would write: name=”John”.

Related Articles


<< Go Back to Bash Variables | Bash Scripting Tutorial

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