FUNDAMENTALS A Complete Guide for Beginners
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.
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.
#!/bin/bash
my_function() {
local x=10 # local variable assignment
echo $x
}
my_function # Output: 10
echo $x # Output: (nothing, variable not defined outside the function)
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.
#!/bin/bash
x=10 # global variable assignment
my_function() {
x=$((x + 5)) # accessing and modifying the global variable
echo $x
}
my_function # Output: 15
echo $x # Output: 15
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:
variable=value
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:
❶ At first, launch an Ubuntu Terminal.
❷ Write the following command to open a file in Nano:
nano single_variable.sh
- nano: Opens a file in the Nano text editor.
- single_variable.sh: Name of the file.
❸ Copy the script mentioned below:
#!/bin/bash
#Assigning integer variable
var_int=23
echo "Student ID: $var_int"
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 u+x single_variable.sh
- 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:
./single_variable.sh
As the image depicts above, the var_int variables return the assigned value 23 as the Student ID.
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) >
#!/bin/bash
#multiple variable in a single line
x=1 y=2 z=3
echo $x
echo $y
echo $z
#Using semicolon sign to separate
var1="Hello"; var2="World"
echo $var1 $var2
#Incorporating read command to assign value
read var3 var4 <<< "Hello LinuxSimply"
echo $var3 $var4
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.
You can follow the steps of Case 01, to save & make the script executable.
Script (var_as_argument.sh) >
#!/bin/bash
# Assigning variables from command-line arguments
name="$1"
age="$2"
city="$3"
# Using the variables
echo "Name: $name"
echo "Age: $age"
echo "City: $city"
The provided Bash script starts with the shebang (#!/bin/bash) to use Bash shell. The script assigns the first command-line argument to the variable name, the second argument to age, and the third argument to city. The positional parameters $1, $2, and $3, which represent the values passed as command-line arguments when executing the script. Then, the script uses echo statements to display the values of the assigned variables.
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:
variable_name=$ENV_VARIABLE_NAME
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.
You can follow the steps of Case 01, to save & make the script executable.
Script (env_variable.sh) >
#!/bin/bash
# Retrieve the value of the environment variable
path_name=$USER
# Use the value in your script
echo "The value of current User is: $path_name"
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.
You can follow the steps of Case 01, to save & make the script executable.
Script (default_variable.sh) >
#!/bin/bash
variable=""
# If a variable is unset or empty, assign it a default value
variable="${variable:-Softeko}"
echo "$variable"
# Set a value to the variable
variable="LinuxSimply"
# Since the variable is not empty, the default value is not used
variable="${variable:-variable}"
echo "$variable"
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.
You can follow the steps of Case 01, to save & make the script executable.
Script (user_variable.sh) >
#!/bin/bash
# Prompt the user for input
echo "Enter your name:"
read name
# Display the value entered by the user
echo "Hello, $name!"
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.
You can follow the steps of Case 01, to save & make the script executable.
Script (let_var_assign.sh) >
#!/bin/bash
# Doing arithmetic operation (Addition)
let "num = 5 + 3"
echo "The value stored in num1 variable is = $num1"
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.
You can follow the steps of Case 01, to save & make the script executable.
Script (shell_command_var.sh) >
#!/bin/bash
# Using backticks
output1=`ls -l`
echo "$output1"
# Using $() syntax
output2=$(date)
echo "$output2"
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.
- Create a Bash script that takes two numbers as input from the user and performs arithmetic operations using variables. The output should look as below:
- Sum: ?
- Difference: ?
- Product: ?
- Quotient: ?
- Remainder: ?
- Write a Bash script to find and display the name of the largest file using variables in a specified directory.
Conclusion
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