Tuesday, 21 June 2011

User Defined Variables in Shell


A variable is name given to the memory location where user defined values can be stored. You can store a value in a variable and later use the variable as a placeholder for that value. Variables are by default allocated memory in RAM and hence volatile.


There are two types of variables in shell
1. System Variables 
2. User defined variables

First we discuss user defined variables

To define User Defined Variable use following syntax

Syntax: 
variable name=value
'value' is assigned to given 'variable name' and Value must be on right side = sign.

Example:
$ num=10#  this is ok
$ 10=num#  Error, NOT Ok, Value must be on right side of = sign.
To define variable called 'student' having value vicky
$ student=vicky
To define variable called n having value 10
$ n=10
$ n = 10 #Spaces should not be present on either s Error. ide of equal to sign


Rules for Defining a variable:
1. Variable name must begin with Alphanumeric character or underscore character (_).
Eg. NUM_=10
  _NAME=KATE
   ROLLNO=42
2.  Don't put spaces on either side of the equal sign when assigning value to variable.
Eg. num = 10 #Error. Spaces on either sides of equal sign.
       num= 10  #Error.Space after equal sign
       num =10  #Error.Space before equal sign.
      num=10   #Perfect 
3. Variables are case-sensitive, just like filename in Linux.
4. You can define NULL variable as follows 
$ student=""
$ student=
5.  Do not use ?,* etc, to name your variable names.

To print or access UDV use following syntax
Syntax: 
$variablename
Consider the example shown below



The output also depends on the type of quotes used. The rules of the quotes are as follows



String in double quotes are printed according to the content considering the $ and \.
Single quotes prints the string as it is without an change.
String enclosed in ` ` executed as commands.For example if the date command is enclosed in ` ` then the date command is excuted.
This example should clear things up.





















Making a script file and executing it.




White space consideration












No comments:

Post a Comment

Popular Posts