How to use Variables in Bash Programming

28/12/2020
Variables work as temporary storage for any programming language. The coder needs to have a clear concept of using different variables in the code. Variables are used to store specific data. The most commonly used data type of variables are integer, string, float, double and Boolean. The data type of any variable has to be defined at the time of variable declaration for strongly type programming languages. But BASH is a weakly typed programming language that does not require to define any data type at the time of variable declaration. So when any numeric value assigns to a variable then it will work as integer and when any text value assigns to a variable then it is string. BASH variables can be used from terminal or on any BASH file. The use of different types of BASH variables are described in this tutorial by using many examples.

Using variable from command line or terminal

You don’t have to use any special character before the variable name at the time of setting value in BASH like other programming languages. But you have to use ‘$’ symbol before the variable name when you want to read data from the variable. You can set and get data from a variable from the terminal in the following way.

Example-1: Declaring and reading string data using variable

Run the following commands from the terminal.

$ myvar="BASH Programming"
$ echo $myvar

Output:

Example-2: Combining two string variables

You don’t have to use any operator to combine two or more strings like other languages. Here, $var1 is used to store string value and $var2 is used to store a numeric value.  Run the following commands from the terminal to combine two variables $var1 and $var2.

$ var1="The price of this ticket is $"
$ var2=50
$ echo $var1$var2

Output:

**Note: You can print the value of the variable without any quotation but if you use quotations then you have to use double quotations.

Example-3: Concatenating strings with variables 

Double quotation can be used to read the value of the variable. In this example, single quotation is used on one echo statement and double quotation is used on another echo statement. Run the following commands from the terminal to check the output.

$ var="BASH"
$ echo "$var Programming"
$ echo ‘$var Programming’

Output:

Example-4: Declaring and reading numeric data using variables

One of the major limitations of Bash programming is that it can’t perform arithmetic operations like other programming languages. Numeric values are taken as strings in BASH. So no arithmetic operation can be done by normal expression and it just combines the numeric values. If you write the expression with double first bracket then the arithmetic operation works properly. Run the following commands from the terminal.

$ n=100
$ echo $n
$ echo $n+20
$ ((n=n+20))
$ echo $n

Output:

Example-5: Doing arithmetic operation using bc command

bc command is another way to do arithmetic operation in BASH. Run the following commands from the terminal. When you use bc command only for doing any arithmetic operation then fractional parts are omitted from the result. You have to use -l option with bc command to get the result with fractional value.

$ n=55
$ echo $n/10 | bc
$ echo $n/10 | bc -l

Output:

Using variables in bash file

You can define variable in bash file by the same way which are mentioned in above examples. You have to create file with .sh or .bash extension to run bash script.

Example-6: Creating simple bash script

Copy the following code in a text editor and save the file with bash extension. In this script, one string and one numeric variables are declared.

str="Learn BASH Programming"
 
#print string value
echo $str
 
num=120
 
#subtract 20 from numeric variable
(( result=$num20))
 
#print numeric value
echo $result

Output:

Example-7: Using global and local variables

In the following script, one global variable n and two local variables n and m are used.
When the function addition() is called then the value of the local variable n is taken for calculation but global variable n remains unchanged.

#!/bin/bash
n=5
function addition()
{
local n=6
local m=4
(( n=n+m ))
echo $n

}
addition
echo $n

Output:

Example-8: Using array variable

Array variable is used to store a list of data. The following example shows how you use of array variable in bash script. The elements of any array are separated by space in BASH. Here, an array of 6 elements is declared. There is no built-in function or property to count the total elements of the array. # with * is used to count total elements. All elements are indicated by *. For loop is used here to iterate the array values. Reading array values and array values with key are shown in the next part of this script.

#!/bin/bash
 
myarr=(HTML JavaScript PHP jQuery AngularJS CodeIgniter)
 
#Count total number of elements of the array
total=${#myarr[*]}
echo "Total elements: $total"
 
#Print each element value of the array
echo "Array values :"
for val in ${myarr[*]}
do
printf "   %sn" $val
done
 
#Print each element value of the array with key
 
echo "Array values with key:"
for key in ${!myarr[*]}
do
printf "%4d: %sn" $key ${myarr[$key]}
done

 

Output:

To use BASH variables properly you need a clear concept on the declaration and use of variables. This tutorial will help you to get a clear idea on BASH variables. After exercising the above examples properly you will be able to use variables more efficiently in your bash scripts.

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

Bash Scripting Tutorial for Beginners

The default command language of Linux is Bash script. We need to run many commands in Linux on a daily basis for many purposes....
29/12/2020

How to compare strings in Bash

For different programming purposes, we need to compare the value of two strings. Built-in functions are used in many programming...
28/12/2020

How to Debug a Bash Script like a Boss

A lot of things can happen in a bash script that unless you know how to debug like a boss, you might as well be up a creek...
29/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

Mua proxy v4 chạy socks5 để chơi game an toàn, tốc độ cao ở đâu?
18/05/2024

Thuê mua proxy Telegram trọn gói, tốc độ cao, giá siêu hời
18/05/2024

Thuê mua proxy Viettel ở đâu uy tín, chất lượng và giá tốt? 
14/05/2024

Dịch vụ thuê mua proxy US UK uy tín, chất lượng số #1
13/05/2024

Thuê mua proxy Việt Nam: Báo giá & các thông tin MỚI NHẤT
13/05/2024