Using Variables in Bash Scripting

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

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
EXPLANATION
  • 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
EXPLANATION

#! /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
EXPLANATION
  • 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 bash script has printed the value of a variable on the terminal.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
EXPLANATION

#! /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 bash script has found that the variable is empty, hence printed a message on the terminal.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
EXPLANATION

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 Bash script has concatenated two variables and then saved them to a variable. And finally printed the variable.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"
EXPLANATION

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 Bash script has taken two number as input to variable and then done the arithmetic summation and multiplication. Afterwards, printed on the terminal.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

Can you declare variables in bash?
Like any other language, you can declare variables in Bash script. You can do various arithmetic operations on these variables as well.
Are bash variables case-sensitive?
Yes, Bash variables are case-sensitive. Here var and Var are two different variables. You have to mention with proper casing to access the right variable.
Do Bash variables have types?
There are mainly two types of variables. They are system-defined variables and user-defined variables. The system-defined variables come with the Bash, and the user-defined variables are set and defined by users.
How does a Bash script work?
A bash script is a file that contains a sequence of commands that are executed by the Bash program line by line. It allows programmers to perform a series of actions.

Related Articles


<< Go Back to Bash Variables | Bash Scripting Tutorial

5/5 - (4 votes)
Susmit Das Gupta

Hello everyone. I am Susmit Das Gupta, currently working as a Linux Content Developer Executive at SOFTEKO. I am a Mechanical Engineering graduate from Bangladesh University of Engineering and Technology. Besides my routine works, I find interest in going through new things, exploring new places, and capturing landscapes. Read Full Bio

Leave a Comment