Saturday 7 July 2012

Shell script - 4

Shell script - 4

To go to Session 1 click here
To go to Session 2 click here
To go to Session 3 click here
To go to UNIX basic commands click here
Online sample UNIX TERMINAL click here

Functions :

           
A function is very use full to break your functionality or program in to little/small programs which will easy to handle. And easy to debug the issue when occurs.

In shell script function can be written with the help of following syntax:

Function_name()
{
            statements
}

Example 13:
#!/bin/sh
funtionone()
{
        echo "I am in funtion one"
        funtiontwo hi how r u
        ret=$?
        echo "funtion two returned $ret"
}
funtiontwo()
{
        echo "I am in funtion two,funtion one called me with $* as arguments i"
        return 1
}
funtionone

Out put:

Testhome/l685360# ./test
I am in funtion one
I am in funtion two,funtion one called me with hi how r u as arguments i
funtion two returned 1
Testhome/l685360#

In the above example 13 there are two functions functionone and functionstwo we call the functionone by the statement funtionone this function in turn calls the second function with arguments “hi how r u” the function two in turn retun back with value 1. I didn’t explain the echo because its all self explanatory.

The sed

            The stream Editor, It is powerful utility of unix, generally used to edit / modify a text files.




The S(Substitution)

Example 14:

Testhome/l685360# vi sed1
Hi baskar,
 i well come u to the festival ,

Testhome/l685360# sed s/baskar/mohan/ <sed1 >sed2
Testhome/l685360# cat sed1
Hi baskar,
 i well come u to the festival ,
Testhome/l685360# cat sed2
Hi mohan,
 i well come u to the festival ,
Testhome/l685360#

In the above example the substitution is used the name baskar in sed1 file  is changed to mohan and saved in another file sed2 the symbol <> refers to redirection look for unix redirection for explanation.


Things to understand
1.      s command
2.      delimiters / / (you can use anything as delimiter as you wish for example (Example 15:
echo jaya | sed s:jaya:jai: ) here we have used : as delimiter)
3.      (baskar) the word to be found
4.      (mohan) the word to be changed finally the command would be
5.      sed s/baskar/mohan/ <inputfile >outputfile
this can also be done for a string for example
           
Example 16:

Testhome/l685360# echo jayachandran | sed s/jaya/jai/
jaichandran
Testhome/l685360#

The &

Example 17:

Testhome/l685360#echo “1365 jai 19b” | sed ‘s/[0-9]*/(&)/’
(1365) jai 19b
Testhome/l685360#

In the above example the sequence or a specific pattern is put between some spl. Char. Like () and so on.


The P

Example 18( without -n):
MTS-REG;titrs105:(l685360)/home/l685360# sed p<sed1
Hi baskar,
Hi baskar,
 i well come u to the festival ,
 i well come u to the festival ,

Example 19( with -n)
MTS-REG;titrs105:(l685360)/home/l685360# sed -n p<sed1
Hi baskar,
 i well come u to the festival ,
MTS-REG;titrs105:(l685360)/home/l685360#

The option p will print the input, if –n is not given the p option alone will make duplicate of each line in the input.


Thanks all...

Don't forget to put your feed back as comments which encourages me to do this and you can also post your questions or solve/give answers for others questions, Thanks in advance friends.....

Shell script - 3

Shell script - 3

To go to Session 1 click here
To go to Session 2 click here
To go to UNIX basic commands click here


Starting with “hello”
            The basic things for any program is input and output this can be achived using the two commands
1.      echo which similar to printf in c
2.      read which similar to scanf in c
First script
Example 7
            #!/bash/sh
            echo “hello”
            echo “Enter ur name”
            read nam
            echo “This is my first program $nam”
The Branching Statements
The next important thing in programming is branching to do a specific task based on specific condition.
1.      if .. fi
2.      if..else..fi
3.      if..elif..else..fi
4.      case..esac

if..fi syntax
if [ condition ]
then
            statements
fi
if..else..fi syntax
if [ condition ]
then
            statements
else
            statements
fi
if..elif..fi syntax
if [ condition ]
then
            statements
elif [ condition ]
            statements
else
            statements
fi

in these condition branching statements can be nested or there may be more than one elif based on requirements.
Example 7:
            #!/bin/sh
            filename=$1
if [-r filename] then
echo "file is readable"
elif [-x filename] then
echo "file is executable"
elif [-w filename] then
echo "file is writable"
else
echo "ERRROR: $filename HAS PERMISSION PROB"
fi
            case..esac syntax
            case variable in
                        pattern1)
                                    statements
                        ;;
                        pattern2)
                                    statements
                        ;;
                        ……
                        ……
                        patternn)
                                    statements
                        ;;
            esac
Example 8:
            #!/bin/sh
            name=$1
            case $name in
                        “jaya”)
                                    echo “Welcome buddy”
                                    ;;
                        “devi”)
                                    echo “Welcome sir”
                                    ;;
                        “Shiv”)
                                    echo “Welcome $name”
                                    ;;
            esac
Output
Testhome/l685360# ./test jaya
Welcome buddy
Testhome/l685360#
           
The looping

            The next important thing in programming is looping to do a specific task for some n times loops available in shell script are:

1.      while
2.      for
3.      unitil
4.      select

While Loop:

            Syntax:
                        While [ condition ]
                        do
                                    statements
                        done

Example 9:

#!/bin/sh
echo "Enter n "
read n
i=0
while [ $i -le $n ]
do
        echo "Welcome"
        i=`expr $i+1 `
done
Out Put:
            Testhome/l685360# ./test
Enter n
2
Welcome
Welcome
Welcome
Testhome/l685360#
*note : break can be used to break the loop
*note : continue can be used to continue the looping without executing the rest of lines.
            Example:
                        n=0
                        While [ $n < 10]
                        do
                                    if[ $n == 1]
                                    then
                                                continue;
                                    fi
                                    #if n==1 n becomes true it goes directly go to continue the loop without incrementing because of this, this loop will be endless loop
                                    n=`expr $n+1`
                        done


For loop:

Example 10:
#i!/bin/sh
n1="0 1 2 3 4 5 6 7 8 9 0 10"
for n in $n1
do
        echo $n
        echo "Welcome"
done

Out put:
Testhome/l685360# ./test
0
Welcome
1
Welcome
2
Welcome
3
Welcome
4
Welcome
5
Welcome
6
Welcome
7
Welcome
8
Welcome
9
Welcome
0
Welcome
10
Welcome
Testhome/l685360#

Until loop:

Until syntax:
 until  [ condition ]
 do
            statements
 done

Example 11:

#!/bin/sh
n = 10
x=0
until [ $x –lt $n ]
do
            echo $x
            x = `expr $x + 1`
done


Select Loop:

Select loop syntax:
select variable in word1 word2 …. Wordn
do
            statements
done

Example 12:

#!/bin/sh
select food in breakfast lunch dinner
do
        if [ $food == "breakfast" ]
        then
                echo "Good morning"
        elif [ $food == "lunch" ]
        then
                echo "Good After noon"
        elif [ $food == "dinner" ]
        then
                echo "Good night"
        else
                echo "Invalid option"
        fi
done
                       
Out put:
Testhome/l685360# ./test
1) breakfast
2) lunch
3) dinner
#? 1
Good morning
#? 2
Good After noon
#? 3
Good night
#?
Don't forget to put your feed back as comments which encourages me to do this and you can also post your questions or solve/give answers for others questions, Thanks in advance friends.....



To go to session 4 click here

Shell script - 2

Shell script - 2
To go to Shell script Session click here
To go to UNIX basic commands click here

Its time to learn operators


 Arithmetic Operator:
           
Symbol
Meaning
+
Addition
-
Minus(subtract)
*
Multiply
/
Divide
%
Modulus
=
Assignment
==
Equal to
!=
Not equal to

In the above the three given in red will be used with comparison and others will be used with expr.

Relation Operators/Comparative operators for numbers/integers:

Operator
Meaning
Usage Example
-eq
Equality condition
[$a –eq $b]
-ne
Not equal condition
[$a –ne $b]
-gt
Greater than condition
[$a –gt $b]
-lt
Less than Condition
[$a –lt $b]
-ge
Greater than equal to condition
[$a –ge $b]
-le
Lesser than equal to condition
[$a –le $b]

Boolean Operators:
Symbol/operator
Meaning
Usage Example
!
Not/Negation
[! [$a –eq $b]] if[$a –eq $b] evaluates to true ! ll make it false and vice versa
-o
OR
[ [$a –eq $b ] –o [-a –eq $c] that is any one condition need to be true
-a
AND
[ [$a –eq $b ] –a [-a –eq $c] that is both condition should be true


Operators used with Strings
Symbol/Operator
Meaning
Usage Example
=
Checks if both strings are equal
[ $str1 = $str2 ]
!=
Checks if both strings are not equal
[ $str1 != $str2 ]
-z
Checks for length is zero
[ $str1 –z $str2 ]
-n
Checks for length is not zero
[ $str1 –n $str2 ]

Files Operators

Symbol/Operator
Meaning
Usage Example
-b file
Checks if the file is block special file
[ -b $filename ]
-c file
Checks if the files is char special file
[ -c $filename ]
-d file
Checks if the file is directory
[ -d $filename ]
-e file
Check for file existence
[ -e $filename ]
-f file
Check if the file is ordinary file
[ -f $filename ]
-g file
Check if the file group id is set
[ -g $filename ]
-p file
Check if the file is a named pipe
[ -p $filename ]
-t file
Check if the file descriptor is open
[ -t $filename ]
-u file
Checks if the files set user id is set
[ -u $filename ]
-r file
Checks if the file is readable
[ -r $filename ]
-s file
Checks if the file size is greater than 0
[ -s $filename ]
-w file
Checks if the file is writable
[ -w $filename ]
-x file
Checks if the file is Executable
[ -x $filename ]

Example 6:
#!/bin/sh
filename=$1
if [-r filename] then
echo "file is readable"
elif [-x filename] then
echo "file is executable"
elif [-w filename] then
echo "file is writable"
else
echo "ERRROR: $filename HAS PERMISSION PROB"
fi


To go to next session click here don't forget to put your feed back as comments which encourages me to do this and you can also post your questions or solve/give answers for others questions, Thanks in advance friends.....




Shell script - 1


Shell script - 1:

          This tutorial will give an over view and a good idea how to write shell script, I think speaking of history like other tutorials is mere waste so I directly starting with details.

If you need any reference or if you are not aware of UNIX basic commands please go through it by clicking here it will be so useful.

#! The she bang

            All shell scripts start with this #! Line this is called she bang it tell the what shell script we are going to use and its location(interpreter location)
            Example 1:
                        #!/bash/sh
            For further reference refer http://en.wikipedia.org/wiki/Shebang_(Unix)

# Comment
            The # is used for commenting the a line
            Example 2:
                        #Adding two numbers

Variables:
            Variable name can contain only, (a to z, A to Z, 0 to 9 and _)


Defining and Assigning values:
            An variable can be defined and assigned as follows
                        Var1=10
                        Var2=”jai”

Variable Types:

When a shell is running, three main types of variables are present:

Local Variables: A local variable is a variable that is present within the current instance of the shell. It is not available to programs that are started by the shell. They are set at command prompt.

Environment Variables: An environment variable is a variable that is available to any child process of the shell. Some programs need environment variables in order to function correctly. Usually a shell script defines only those environment variables that are needed by the programs that it runs.

Shell Variables: A shell variable is a special variable that is set by the shell and is required by the shell in order to function correctly. Some of these variables are environment variables whereas others are local variables.

Command line arguments and some special symbols with $

Example program 3:
#!/bin/sh
echo "file name: $0"
echo "first argument: $1"
echo "Second argument: $2"
echo "Number of arguments: $#"
echo "All the arguments individually double quoted: $@"
echo "Process number of previous command:$!"
echo "Process number of CURRENT SHELL: $$"
echo "All the arguments double quoted: $*"



Out put:
Testhome/l685360# ./test jaya chandran
file name: ./test
first argument: jaya
Second argument: chandran
Number of arguments: 2
Given argument is: jaya chandran
Process number of previous command:
Process number of CURRENT SHELL: 20775420
All the arguments: jaya chandran
Testhome/l685360#

Arrays:

Example 4:
#!/bin/sh
name[0]="jayachandran"
name[1]="Mohan"
name[2]="Devi"
name[3]="Shiva"
name[4]="Ranjith"
echo ${name[@]}
echo ${name[*]}
Output
Testhome/l685360# ./test
Mohan Devi Shiva Ranjith
Mohan Devi Shiva Ranjith
Testhome/l685360#

Arithmetic and Relation operators:
The bourne shell does not do any arithmetic it uses external programs expr and awk to the arithmetic

expr
Example 5:
#!/bin/sh
val1=2
val1=`expr $val1 + 10`
echo "value of val1 aft adding 10 is : $val1"
            Out put:
                        Testhome/l685360# ./test
value of val1 aft adding 10 is : 12
Testhome/l685360#

In the above program we can see usage of expr
1.                          Any arithmetic expression with symbols should be separated by space.( $val1 + 10 )
2.                          Any expr should be given in between `` only.

To go to next session click here don't forget to put your feed back as comments which encourages me to do this and you can also post your questions or solve/give answers for others questions, Thanks in advance friends.....