Shell Scripting Lesson 4 - Variables

Variables are used to keep some information in RAM.There are tow types of Variables in Linux System.

System Variables - These variables are created and maintained by Linux System. Following Variables are Commonly used in our Shell Programming.

Ex :
BASH=/bin/bash  - Shell Name
HOME=/home/etutionlk  - Home directory
PWD=/home/etutionlk/shell  - Current Working Directory
PATH=/sbin:/bin:/usr/sbin:/usr/java/jdk/bin  - Path Settings are stored.

There are few more variables other than above variables. These variables are defined in CAPITAL LETTERS.



User Defined Variables - These type of variables are defined and maintained by user. User can any number of variables.

Ex :
NUMBER=10
FACTORIAL=5

How to define Variable ?

variable_name=value

No Spaces are allowed in between variable name and '=' sign... !
Ex:

#!/bin/sh
HELLO="Hello World" 
echo $HELLO

Shell Variables are case sensitive. Variable VAR1 and var1 are treated as two different variables.

How To create NULL variables ?
Define a variable with no values.

Ex :
VAR=""

How To use User Defined Variable in shell terminal ?
Use $ sign before the variable name.

Ex : 
echo $VAR

How Create Read Only Variables ?
Use readonly keyword before the variable name.

Ex :
#!/bin/sh

NAME="etutionlk"
readonly NAME
NAME="etution lanka"

This Gives error Message.

/bin/sh: NAME: This variable is read only.

What is unset keword ?
unset keyword is used to unset or delete Variable from variable list. Once you unset a Variable you can not get values of that variable.

Ex :
#!/bin/sh
NAME="etutionlk"
unset NAME
echo $NAME

How do simple mathematical operations with variables ?

Ex : num1=10 , num2 = 20  Calculate num1 + num2

num1=10

num2=20

expr $num1+$num2

Have a Fun with Simple Calculations with shell scripting Variables.


To Ask Anything about  Tutorial, Drop a Comment !

0 comments:

Post a Comment

Ask anything about this Tutorial.