Tuesday, April 2, 2013

Shell Scripting 02: Playing with variables

In a shell, one can use variables to store temporary data. In shell you don't need to declare variables. You just use variables where ever you want. In fact you declare variables by initializing it. Within the shell you can access the contents of a variable by preceding its name with a $. Whenever you extract the contents of a variable, you must give the variable a preceding $. IN order to assign a value to a variable just use the variable name. In a shell all the variables are considered and stored as string.

Try the following in your shell

anil@anil-VirtualBox:~/script_test$ tempvar=ANIL   
anil@anil-VirtualBox:~/script_test$ echo $tempvar  

In the above example a variable named tempvar is created by assigning the string ANIL to it. In the echo command this variable is accessed by prefixing it with a '$' sign. If here are white spcaes in the string, then it should be enclosed in quotes as shown below

anil@anil-VirtualBox:~/script_test$ tempvar="ANIL C S"
anil@anil-VirtualBox:~/script_test$ echo $tempvar  
ANIL C S                                              

It is important to note that there should not be any space on either side of the '=' sign.

You can also assign user input to a variable using the 'read' command. Read command accepts one parameter as the variable name and waits for user to enter some text. The text is terminated by pressing enter.

anil@anil-VirtualBox:~/script_test$ read tempvar  
anil@anil-VirtualBox:~/script_test$ echo $tempvar 

Environment variables
When a shell is started by default some variable are populated. Some of these are listed below.


Contains the path to the users home folder


A contains a list of directories to search for commands

With these ideas in mind lets modify our previous helloworld script as shown below

#This script by default print Hello world. If a parameter
#is supplied then it prints the parameter text instead of
#Hello World                                             
if [ -z $1 ]                                             
echo "Hello World"                                       
echo "Printing the fist parameter.. $1"                  
exit 0                                                   

In this script first line
if [ -z $1 ]
is a condition check. Condition is given in []. Here $1 is an environment variable which holds the first parameter passed to the script. -z option will cause the condition to return true if the following string is empty. If the condition check returns true, the commands following then will be executed. In short the above script checks whether the first parameter is empty or not. If the first parameter is empty it will print "Hello World" else it will print the parameter text.

Try out this script in your shell.


Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | coupon codes