Variables in Shell Script - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

demo-image

Variables in Shell Script

Share This

Before going through a language in detail, you should understand the concept of variables. A variable is used to store data, which can be changed later. In the Linux environment there are two types of variables:


System Variables

These types of variables are defined by Linux Operating System. Generally, capital letters are used for system variables.

For example, BASH, BASH_VERSION, HOME, LOGNAME, etc.

1
2
3
4
5
6
7
8
#!/bin/bash
echo $BASH
echo $BASH_VERSION
echo $HOME
echo $LOGNAME
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

The output of the program is shown below:

system_vars

User Defined Variables

These types of variables are defined by users. Generally, lowercase letters are used to define the variables. A name of a variable can be started with only letters (a to z or A to Z) and the underscore. But it can contain digits (0 to 9) in any other position, except the starting position.

A user-defined variable can be declared as:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/bin/bash
count=100
echo $count
str1="One String"
echo $str1
str2='Another String'
echo $str2
str3=hello
echo $str3
str4=one+two+three
echo $str4
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Array

An array is a collection of homogeneous data stored in contiguous memory space. The following example shows, how data is stored in memory.

In the shell script, the first element is stored at index 0.


1
2
3
4
5
6
7
8
9
10
#!/bin/bash
lang[0]="C"
lang[1]="C++"
lang[2]="Java"
lang[3]="Python"
echo ${lang[2]}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

The example shown above will print 3rd element of the array.

To print all the elements of the array, you can use echo ${lang[@]} or echo ${lang[*]}.

Read-only variables

The value of a read-only variable can't be changed.


1
2
3
4
5
6
7
#!/bin/bash
str="Hello"
read-only str
echo $str
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Unsetting variables


1
2
3
unset var_name
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Shell script to swap two numbers

1
2
3
4
5
#!/bin/bash
# Program name: "swap.sh"
# shell script program to swap two numbers.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
swap


Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.