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.....



Wednesday 21 March 2012

Bulls and Cows

Click here to see the rules for 4numbers. Here i am giving the code for n number of char string hope it will be useful for many.....this is written using visual studio c++ so do the needed change if you try the code with other compilers.............


To learn UNIX basic commands click here

To learn Shell Script click here


// bullandcow.cpp : Defines the entry point for the console application.

//

#include"stdafx.h"
#include<string.h>
//#include<conio.h>
#include<stdlib.h>
int

_tmain(int argc, _TCHAR* argv[])
{

int n,ch=1,i,j,temp[10],t=0;
int cow=0,buff=0,count=0;
char word[10],check[10];
printf("Hi welcome to cow and bull game\n");
printf("Instructions for player 1:\n");
printf("Make sure player two is not when you r entering the word you think \n **note: no character should repet\n");
printf("\n\nInstructions for player 2:\n");
printf("You have 10 chance to find the word \n");
gets(word);
n=(int)strlen(word);
for(i=0;word[i]!='\0';i++)
{
for(j=i;word[j]!='\0';j++)
{
if(word[i]==word[j])
{
if(i!=j)
{
printf("Fatal error: The input word has char repeted start again");
getch();
exit(0);
}
}
}
}
//clrscr();
system("cls");
printf("\nWelcome Player - 2 you have 5 chances \n");
while(ch<=15)
{
printf("\nEnter the word gussed with %d char",n);
gets(check);
if(strlen(check)!=n)
{
printf("Error\n");
exit(0);
}
for(i=0;word[i]!='\0';i++)
{
for(j=0;check[j]!='\0';j++)
{
if(word[i]==check[j])
{
if(i==j)
{
cow=cow+1;
break;
}
else if(i!=j)
{
buff=buff+1;
break;
}
}
}
}
if(cow==n)
{
printf("Great job");
getch();
exit(0);
}
else
{
printf("cow:%d,buff:%d",cow,buff);
}
cow=0;buff=0;
ch++;
}
return 0;
}

Sunday 4 March 2012

Online Unix Terminal

As i seen many questions regarding a UNIX terminal or equivalent i made a research and find out one this will be help full for beginners. drawback of this is some commands do not work in this.


UNIX like terminal called jsuix

To learn UNIX basic commands click here

To learn Shell Script click here



click the above link and click the >open terminal
go ahead and practice basic unix commands.

this terminal is fully written in java script.

Tuesday 28 February 2012

Unix Basics session 2

Click here for Unix session 1

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



Visual editor
                Helps in              
                                Inserting and deleting text
                                Replacing text
                                Moving around a file
                                Finding and substituting string
                                Cutting and pasting text
                                Reading and writing to other text

                While working in vi editor the content of the current file is stored in buffer and we work on that only atlast we may save the changes or quit without saving
Vi editor mode
                Command mode – in this what ever been typed is interpreted as command only cant insert data into file
                Insert mode – to enter into insert mode press ‘I’ in this mode what ever u type is included as text into file to exit from this mode press escape
                Ex command mode – this allows us to give commands the end of the editor we these types of command and these command starts with :
Starting vi deitor
Vi filename – creates a new file
View filename – view file in read only mode
Exiting vi editor
                :w – write the buffer to disk
                :w filename – write the buffer in the given filename
                :wq - write the buffer to disk and quit
                :zz - write the buffer to disk and quit
                :q! – quit without writing edit buffer to disk.
To insert text vi editor
                a – append text after cursor
                A – append text at the end of line
                i – insert before cursor
                I – insert text beginning of line
                o – open a blank line after the current line for the text input
                O - open a blank line before  the current line for the text input
Deleting text
                x- delete charac at cursor
                dh- delete char before cursor
                nx-delete n char at cursor
                dw- delete next word
                db- delete previous word
                dnw- delete n words from cursor
                dnb- delete n words before cursor
                d0- delete to beginning of line
                d$- delete to end of line
                D- delete to end of line
                dd- delete current line
                d(- delete beginning of sentence
                d)- delete to end of sentence
                d{- delete to beginning of paragragh
                d}- delete to end of paragragh
                ndd- delete to lines(starts at the current line)
copy  lines
                yy- copy 1 line to buffer
                nyy- copy n lines ro buffer
                P- out the contents in buffer aft current line
                p- put the contents in buffer before current line
cut and paste
                ndd – cuts/deletes n lines and places it in buffer
                P- out the contents in buffer aft current line
                p- put the contents in buffer before current line
Find and replace
                /str – search forward for str
                ?str – search backward for str
                N – repeat the previous search in reverse direction
                n- find the next occurrence of current string
:s/old/new find and replace first occurrence in current line
:s/old/new/g  find and replace all occurrence in current line
%s/old/new/g find and replace of all occurrence in current file
%s/old/new/gc find and replace of all occurrence in current file with y/n option prompt before every replace.

Setting options
                :Set ai – set auto indent
                 :Set noai– set off auto indent
                :set nu- set line number on
                :set nonu- set off  line number
                :set scroll=n set the number of lines to be scrolled
                :set sw=n set width to n;
                :set wm= set wrapmargin to n .

Unix access and permissions
                Unix is a multi user system.  Each file and directory In unix can be used by many users.               
Permissions  for file or folder are
                r – read
                w- write
                x- execute
permissions are controlled at three level
                u- user
                g- group
                o-others
ls –l displays file/folder permission
                drwxrwxrwx  in this d denotes  directory, rwx denotes (read,write,execute)  permission for user ,  rwx denotes (read,write,execute)  permission for group, , rwx denotes (read,write,execute)  permission for owner
chmod command
                used to change the permission of a file or folder
                chmod a+r jc.txt adds read permission to all users
                chmod o-r jc.txt removes/revokes read permission for others
                chmod og+rx jaya.txt adds read and execute permissions for group and others
                chmod +w * add write permission to all files for users.
Permissions by numerical or octal
                File access permissions can also be given using numerical or octal values
Permission and values:
                r- 4(read only)
                w-2
                x-1
0 – no permission
1 – execute
2 – write only
3 – write and execute (1+2)
4 – read only
5 – read and execute (4+1)
6- read and write(4+2)
7 – read,write and execute(4+2+1)
E.g chmod 777 jayachandran.txt
The above example gives read,write and execute permission to all (owner,user,others)

Process
                Instance of an executing a program is called process.
                A program called SCHEDULER runs in the memory and decides which process should get the CPU

Process ID
In unix every process has a unique id called process id.
Command ps:
                Ps – shows list of process running with its id time and command
                optiions
                                -a process of all users
                                -u username process of a particular user
                                -t tty –process of a particular terminal
                                -f full listing of information
                                -e listing of the system process (Daemons)
Kill command
                Kill – command is used to send a signal to a process mostly this will be kill signal.
                Syntax
                                Kill [signal] pid
                Signal
                STOP
                CONT
                -l
SHELL
                When ever you log in you are placed in a shell, shell works as an interpreter , every command we enter is passed to operating system.
                To determine your shell
                                Echo $SHELL
Types of shell
                Bourne shell
                C shell
                Korn shell
                Tc shell
                Bourne again shell

Communication in UNIX
                Write – two way communication with any person who is currently logged on.
                                write – username
                mesg – controls the messages sent by other users
                                mesg n – prevents others user to write to your terminal.
                                mesg y – allows other users to write to your terminal
                mail – to send mail to user you can send mail even if that user is not logged in.
                                mail username
                                subject: <subject of mail>
                                  <text>
                               <ctrl+d to exit from mail >
                                to do this you need mailx in your system