Home > Bash Scripting Tutorial > Bash Variables > Variable Declaration and Assignment > How to Assign Variable in Bash Script? [8 Practical Cases]
How to Assign Variable in Bash Script? [8 Practical Cases]
Variables allow you to store and manipulate data within your script, making it easier to organize and access information. In Bash scripts , variable assignment follows a straightforward syntax, but it offers a range of options and features that can enhance the flexibility and functionality of your scripts. In this article, I will discuss modes to assign variable in the Bash script . As the Bash script offers a range of methods for assigning variables, I will thoroughly delve into each one.
Table of Contents
Key Takeaways
- Getting Familiar With Different Types Of Variables.
- Learning how to assign single or multiple bash variables.
- Understanding the arithmetic operation in Bash Scripting.
Free Downloads
Local vs global variable assignment.
In programming, variables are used to store and manipulate data. There are two main types of variable assignments: local and global .
A. Local Variable Assignment
In programming, a local variable assignment refers to the process of declaring and assigning a variable within a specific scope, such as a function or a block of code. Local variables are temporary and have limited visibility, meaning they can only be accessed within the scope in which they are defined.
Here are some key characteristics of local variable assignment:
- Local variables in bash are created within a function or a block of code.
- By default, variables declared within a function are local to that function.
- They are not accessible outside the function or block in which they are defined.
- Local variables typically store temporary or intermediate values within a specific context.
Here is an example in Bash script.
In this example, the variable x is a local variable within the scope of the my_function function. It can be accessed and used within the function, but accessing it outside the function will result in an error because the variable is not defined in the outer scope.
B. Global Variable Assignment
In Bash scripting, global variables are accessible throughout the entire script, regardless of the scope in which they are declared. Global variables can be accessed and modified from any script part, including within functions.
Here are some key characteristics of global variable assignment:
- Global variables in bash are declared outside of any function or block.
- They are accessible throughout the entire script.
- Any variable declared outside of a function or block is considered global by default.
- Global variables can be accessed and modified from any script part, including within functions.
Here is an example in Bash script given in the context of a global variable .
It’s important to note that in bash, variable assignment without the local keyword within a function will create a global variable even if there is a global variable with the same name. To ensure local scope within a function , using the local keyword explicitly is recommended.
Additionally, it’s worth mentioning that subprocesses spawned by a bash script, such as commands executed with $(…) or backticks , create their own separate environments, and variables assigned within those subprocesses are not accessible in the parent script .
8 Different Cases to Assign Variables in Bash Script
In Bash scripting , there are various cases or scenarios in which you may need to assign variables. Here are some common cases I have described below. These examples cover various scenarios, such as assigning single variables , multiple variable assignments in a single line , extracting values from command-line arguments , obtaining input from the user , utilizing environmental variables, etc . So let’s start.
Case 01: Single Variable Assignment
To assign a value to a single variable in Bash script , you can use the following syntax:
However, replace the variable with the name of the variable you want to assign, and the value with the desired value you want to assign to that variable.
To assign a single value to a variable in Bash , you can go in the following manner:
Steps to Follow >
❶ At first, launch an Ubuntu Terminal .
❷ Write the following command to open a file in Nano :
- nano : Opens a file in the Nano text editor.
- single_variable.sh : Name of the file.
❸ Copy the script mentioned below:
The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. Next, variable var_int contains an integer value of 23 and displays with the echo command .
❹ Press CTRL+O and ENTER to save the file; CTRL+X to exit.
❺ Use the following command to make the file executable :
- chmod : changes 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.
- single_variable.sh : File name to which the permissions are being applied.
❻ Run the script by using the following command:
Case 02: Multi-Variable Assignment in a Single Line of a Bash Script
Multi-variable assignment in a single line is a concise and efficient way of assigning values to multiple variables simultaneously in Bash scripts . This method helps reduce the number of lines of code and can enhance readability in certain scenarios. Here’s an example of a multi-variable assignment in a single line.
You can follow the steps of Case 01 , to save & make the script executable.
Script (multi_variable.sh) >
The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. Then, three variables x , y , and z are assigned values 1 , 2 , and 3 , respectively. The echo statements are used to print the values of each variable. Following that, two variables var1 and var2 are assigned values “ Hello ” and “ World “, respectively. The semicolon (;) separates the assignment statements within a single line. The echo statement prints the values of both variables with a space in between. Lastly, the read command is used to assign values to var3 and var4. The <<< syntax is known as a here-string , which allows the string “ Hello LinuxSimply ” to be passed as input to the read command . The input string is split into words, and the first word is assigned to var3 , while the remaining words are assigned to var4 . Finally, the echo statement displays the values of both variables.
Case 03: Assigning Variables From Command-Line Arguments
In Bash , you can assign variables from command-line arguments using special variables known as positional parameters . Here is a sample code demonstrated below.
Script (var_as_argument.sh) >
Case 04: Assign Value From Environmental Bash Variable
In Bash , you can also assign the value of an Environmental Variable to a variable. To accomplish the task you can use the following syntax :
However, make sure to replace ENV_VARIABLE_NAME with the actual name of the environment variable you want to assign. Here is a sample code that has been provided for your perusal.
Script (env_variable.sh) >
The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The value of the USER environment variable, which represents the current username, is assigned to the Bash variable username. Then the output is displayed using the echo command.
Case 05: Default Value Assignment
In Bash , you can assign default values to variables using the ${variable:-default} syntax . Note that this default value assignment does not change the original value of the variable; it only assigns a default value if the variable is empty or unset . Here’s a script to learn how it works.
Script (default_variable.sh) >
The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The next line stores a null string to the variable . The ${ variable:-Softeko } expression checks if the variable is unset or empty. As the variable is empty, it assigns the default value ( Softeko in this case) to the variable . In the second portion of the code, the LinuxSimply string is stored as a variable. Then the assigned variable is printed using the echo command .
Case 06: Assigning Value by Taking Input From the User
In Bash , you can assign a value from the user by using the read command. Remember we have used this command in Case 2 . Apart from assigning value in a single line, the read command allows you to prompt the user for input and assign it to a variable. Here’s an example given below.
Script (user_variable.sh) >
The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The read command is used to read the input from the user and assign it to the name variable . The user is prompted with the message “ Enter your name: “, and the value they enter is stored in the name variable. Finally, the script displays a message using the entered value.
Case 07: Using the “let” Command for Variable Assignment
In Bash , the let command can be used for arithmetic operations and variable assignment. When using let for variable assignment, it allows you to perform arithmetic operations and assign the result to a variable .
Script (let_var_assign.sh) >
The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. then the let command performs arithmetic operations and assigns the results to variables num. Later, the echo command has been used to display the value stored in the num variable.
Case 08: Assigning Shell Command Output to a Variable
Lastly, you can assign the output of a shell command to a variable using command substitution . There are two common ways to achieve this: using backticks ( “) or using the $() syntax. Note that $() syntax is generally preferable over backticks as it provides better readability and nesting capability, and it avoids some issues with quoting. Here’s an example that I have provided using both cases.
Script (shell_command_var.sh) >
The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The output of the ls -l command (which lists the contents of the current directory in long format) allocates to the variable output1 using backticks . Similarly, the output of the date command (which displays the current date and time) is assigned to the variable output2 using the $() syntax . The echo command displays both output1 and output2 .
Assignment on Assigning Variables in Bash Scripts
Finally, I have provided two assignments based on today’s discussion. Don’t forget to check this out.
- Difference: ?
- Quotient: ?
- Remainder: ?
- Write a Bash script to find and display the name of the largest file using variables in a specified directory.
In conclusion, assigning variable Bash is a crucial aspect of scripting, allowing developers to store and manipulate data efficiently. This article explored several cases to assign variables in Bash, including single-variable assignments , multi-variable assignments in a single line , assigning values from environmental variables, and so on. Each case has its advantages and limitations, and the choice depends on the specific needs of the script or program. However, if you have any questions regarding this article, feel free to comment below. I will get back to you soon. Thank You!
People Also Ask
Related Articles
- How to Declare Variable in Bash Scripts? [5 Practical Cases]
- Bash Variable Naming Conventions in Shell Script [6 Rules]
- How to Check Variable Value Using Bash Scripts? [5 Cases]
- How to Use Default Value in Bash Scripts? [2 Methods]
- How to Use Set – $Variable in Bash Scripts? [2 Examples]
- How to Read Environment Variables in Bash Script? [2 Methods]
- How to Export Environment Variables with Bash? [4 Examples]
<< Go Back to Variable Declaration and Assignment | Bash Variables | Bash Scripting Tutorial
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 Cancel reply
Save my name, email, and website in this browser for the next time I comment.
Get In Touch!
Legal Corner
Copyright © 2024 LinuxSimply | All Rights Reserved.
IMAGES
VIDEO