Wednesday, April 6, 2011

Overview about variables in shell script

Variables meaning and its use are more or less similar like other programming language variables. As usual variables are used to hold values. Like other programming languages, shell script doesn't require you to declare the variables.Value of the variables can be retrieved by placing $ (dollar) symbol in front of the variable.

Rules governing variables:
a. Variables name should start either with character or underscore
b. While assigning the value to a variable, no space should be left between the left and right hand side of "=" operator.
c. While assigning the value to a variable, required quotes should be provided to avoid the error. If value has space in between them, then value should be enclosed in quotes.

eg: 
"country" and "same" are variable names.

volcano@volcano-laptop:~/shellscript$ country=India
volcano@volcano-laptop:~/shellscript$ echo $country
India
volcano@volcano-laptop:~/shellscript$ same=$country
volcano@volcano-laptop:~/shellscript$ echo $same
India

volcano@volcano-laptop:~/shellscript$ name=sujay kumar
kumar: command not found
volcano@volcano-laptop:~/shellscript$ echo $name

volcano@volcano-laptop:~/shellscript$ name="Sujay Kumar"
volcano@volcano-laptop:~/shellscript$ echo $name
Sujay Kumar

Example for variables in a shell script:

volcano@volcano-laptop:~/shellscript$ cat vari.sh
#!/bin/bash
#variable declaration, assignment, & retrieval of value
country=India
echo $country
same=$country
echo $same
name="Sujay Kumar"
echo $name
volcano@volcano-laptop:~/shellscript$ ./vari.sh
India
India
Sujay Kumar
volcano@volcano-laptop:~/shellscript$

5 comments: