Friday, July 4, 2008

Shell Script Basics

How to write the Shell Script ? You can use any of the available editors to write the shell script. Just write down the shell script save it as the filename.vi.

To execute the file use ./filename.sh at terminal window.

But before you execute the file you must have the execute permission of the file. So first write down the following command

chmod u+x filename

How to comment the line?

# is used to put the comment in the code

How to read the line? Read variable-name

How to print the line? Echo “Shell Script “ # will simple print the line Echo –e “\n Shell Script” # to use other formatters like “\n”, “\t” etc.. use echo –e Echo “$a”

How to assign the value to variable? a=0 # right way to assign the value to variable a= 0 # Error, Space after ‘=’ a =0 # Error, Space after ‘a’

Another thing Shell script is case sensitive. Means the no, No, nO and NO all are different variable and not the same.

How to assign the Value return by some command? You can’t directly assign the value to by some command to any variable as we done above.

a=expr 1 + 1 # this will gives you error

you needs to put the command in the `` ( quotes ). Like follows

a=`expr 1 + 1` #correct way echo $a # will print the 2

What is Command Line argument and how to pass it? Command line argument is nothing but the argument you pass with you program as a value or to change to flow of program.

For example when you use rm filename command. rm is the executable file which removes the other files. While filename is the arguments that shows which file to delete. Now you know why command line is used.

All the arguments you pass are stored in the special variables. Below are some of them

$1,$2….. Command line arguments you pass with program. $0 program. Name

$# Number of the arguments you passed

A sample program.

add.sh

if [ $# -ne 2 ]; then

echo “Usage: $0 Num1 Num2”

fi

expr $1 + $2 # adds the first and second arguments and print the sum.

Don’t worry if you are not getting the if condition and expr right now. We will cover it soon. To Execute the above program.

./add.sh 10 10

This will print the 20 as output.

No comments: