FUNDAMENTALS A Complete Guide for Beginners
The variable is one of the integrated parts of the Bash scripting. It eases the primary purpose of a Bash script by making it more robust to solve complex problems, automating long tasks, etc. Programmers can take input into a variable, manipulate the value of the variables, and save important data to a variable. Having good practice on Bash variables make Bash programmer more efficient. In this article, I will explore various aspects of using variables in Bash script.
Key Takeaways
- Getting familiar with the usage of variables in Bash.
- Getting familiar with the process of doing mathematical operations of Bash variables.
Free Downloads
Handling Variables Using Bash Scripts
Variable is one of the most important part of Bash script. Bash Programmer can do various activities like storing data to a variable, doing arithmetic operations, etc. Some common practices of Handling variables using bash scripts are given below.
a. Printing Bash Variable on the Terminal
You can easily print the value of a Bash variable on the terminal. To do so, you have to execute the following command into the terminal.
echo $variable_name
b. Check Whether a Bash Variable is Empty
You can check whether a variable contains a value. It is important when you want to store data in a variable. If you overwrite a variable, the previous value will be lost.
c. Saving Output to Variable
Sometimes, you might have important data, and you need to save it for later. In such a case, you can save the value to a variable.
d. Arithmetic Operation of Variable
You can do the arithmetic operation of the variable to achieve some calculation of finance or scientific purposes. Here the result can also be saved to a variable.
e. Replace String in Bash Variable
Sometimes, your string may contain unnecessary parts, and you might need to replace this part with the correct string. You can replace your desired part of a line. You can execute the following code to do this.
line=$(sed "s/$replace/s//$replacewith/" <<< "$line")
f. Variable Expansion in Bash Scripts
Parameter expansion can modify, expand or replace the value of the parameter. The parameter expansions can be used for various purposes. Some of them are given below.
Parameter Expansion | Description |
${variable:=value} | If the variable is unset or undefined, set the value to the variable. |
${#variable} | Count the length of the variable. |
${variable/pattern/string} | Replace the part of the variable with a string where the pattern match for the first time. |
4 Practical Examples of Using Variables in Bash Scripts
Using variables in Bash script is a powerful tool for Bash programmers. It makes the script more concise. Some practical examples of using variables in Bash are given below.
Example 01: Printing Variable Value on the Terminal
You can easily print the value of a variable on the terminal. I have developed a Bash script that prints a variable value on the terminal. To achieve so, follow the below procedures.
Steps to Follow >
❶ At first, launch an Ubuntu Terminal.
❷ Write the following command to open a file in Nano:
nano var1.sh
- nano: Opens and creates a file in the nano text editor.
- var1.sh: File name.
❸ Copy the script mentioned below:
#! /bin/bash
#setting variable
a=”Welcome to Linuxsimply!”
#printing variable
echo$a
#! /bin/bash interprets it is a Bash script. Then the value of variable a is set. Then the value of a is printed on the screen with the help of 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 +x var1.sh
- chmod: Changes the permissions of files and directories.
- +x: Argument with the chmod command to add the executable permission.
- var1.sh: File that you want to make executable.
❻ Run the script by the following command:
./var1.sh
The image shows that the Bash script has printed the value of a variable on the terminal.
Example 02: Check Whether a Bash Variable is Empty
Checking a Bash variable, whether empty or not, is crucial. Here, I have developed a Bash script that can perform the task. To do so, use the below script.
You can follow the steps of Example 1, to save & make the script executable.
Script (var2.sh) >
#!/bin/bash
#NULL is set as the value of var variable
var=""
if [ -n "$var" ]; then
#check the value of var variable if found then print this line with the value of var on the terminal
echo "Variable is $var"
else
#if the value of var is not found means it is empty, then prints this line on the terminal
echo "Variable is empty"
fi
#! /bin/bash ‘#!’, is called shebang or hashbang. It indicates the interpreter to be used for executing the script, in this case, it’s bash. Then var=”” command set NULL as the value of var variable. Then, if [ -n “$var” ]; then echo “Variable is $var” command checks the value of var variable if found then print this line with the value of var on the terminal. If the variable is empty then the else echo “Variable is empty” command prints this line on the terminal.
Now, you can simply run the script file from your command line by executing:
./var2.sh
The image shows that the Bash script has checked whether a Variable is empty and printed a message on the terminal.
Example 03: Save Output to Bash Variable
You can save output value to a variable. Here I have developed a Bash script that concatenates two strings to a variable, then saves it to a variable. To know more, follow the below script.
You can follow the steps of Example 1, to save & make the script executable.
Script (var3.sh) >
#!/bin/bash
#setting value of the variable
a="Happy"
b="Scripting"
#concatenating then keeping value to variable c
c=$a$b
#printing value of c
echo $c
Initially, two variable named a and b is created. Then they are concatenated into a single variable named c. Afterward, the value of c is printed.
Run the script by the following command:
./var3.sh
The image shows that the Bash script has concatenated two variables and then saved them to a variable. And finally printed the variable.
Example 04: Perform Arithmetic Operation Using Variables in Bash Script
You can take a number as input to the Bash variable, then do some Arithmetic operations. Here I have developed a Bash script that takes two input to variables and then performs arithmetic summation and multiplication. To do the same, follow the below script.
You can follow the steps of Example 1, to save & make the script executable.
Script (var4.sh) >
#!/bin/bash
#read input from the user
read -p "Enter The First Number:" n1
read -p "Enter The Second Number:" n2
#addition
sum=$((n1 + n2))
echo "Summation of the Two Numbers: $sum"
#multiplication
product=$((n1*n2))
echo "Multiplication of the Two Numbers: $product"
At first, two variables named n1 and n2 are taken as input from the user. Then summation and multiplication are calculated and printed.
Run the script by the following command:
./var4.sh
The image shows that the Bash script has taken two variables as input and then done the arithmetic summation and multiplication.
Conclusion
In summary, mastering variables in Bash is essential for effective scripting. They form the backbone of dynamic interactions, enabling efficient data manipulation and code reuse. With this skill, you can create adaptable and efficient Bash scripts that unlock the full potential of command-line tasks, enhancing productivity and automation.
People Also Ask
Related Articles
- How to Echo Variables in Bash Script? [4 Practical Examples]
- How to Use String Variables in Bash Script? [4 Cases]
- How to Append String to Bash Variable? [2 Effective Ways]
- How to Check If Bash Variable Exists? [2 Effective Methods]
- How To Check if Bash Variable is Empty? [2 Easy Methods]
- How to List and Set Bash Environment Variables? [3 Methods]
- 2 Ways to Unset Environment Variables Using Bash Script
- 5 Methods to Check If Environment Variable is Set in Bash Script
- How to Set Bash $PATH Variable? [Easiest Configuration]
- 2 Cases to Execute Command Stored in Bash Variable
- How to Store Command Output to Bash Variable? [3 Examples]
- How to Read a File into Bash Variable? [2 Simple Methods]
- How to Write Bash Variable to File? [3 Effective Methods]
- Compare Variables in Bash Scripts [3 Practical Cases]
- Increment Variable Value in Bash Scripts [4+ Examples]
- Adding 1 to Bash Variable [3 Examples]
- Decrement Variable Value in Bash Scripts [4+ Examples]
- Addition of Bash Variable [4+ Examples]
- How to Subtract Two Bash Variables? [4+ Easy Approaches]
- How to Multiply Variable in Bash [6+ Practical Examples]
- Variable Substitution in Bash [Replace Character & Substring]
<< Go Back to Bash Variables | Bash Scripting Tutorial