Variables in Shell Script - BunksAllowed

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

Random Posts

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.

#!/bin/bash echo $BASH echo $BASH_VERSION echo $HOME echo $LOGNAME

The output of the program is shown below:

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:


#!/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

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.


#!/bin/bash lang[0]="C" lang[1]="C++" lang[2]="Java" lang[3]="Python" echo ${lang[2]}

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.


#!/bin/bash str="Hello" read-only str echo $str

Unsetting variables


unset var_name

Shell script to swap two numbers

#!/bin/bash # Program name: "swap.sh" # shell script program to swap two numbers. read num1 read num2 echo "Before Swapping" echo "Num1: $num1" echo "Num2: $num2" num1=$(($num1 + $num2)) num2=$(($num1 - $num2)) num1=$(($num1 - $num2)) echo "After Swapping" echo "Num1: $num1" echo "Num2: $num2"


Happy Exploring!

No comments:

Post a Comment