unix.pdf

115
Importance of unix: 1) Unix is virous free os, so high security for dat a. 2) Unis is stable os, it can run continuously with same performance. 3) Admi., cost is less for unix servers 4) Unix source code is open.ANy one can modify the source code of unix. flavor of unix: operationg system developed based on unix source code. Ex: Linux, solaris, Hp-UX, IBM-AIX,MACosx,sco unix etc., fl= core unix comds + fl commands + designed for di fferent H/w. Linux = unix + GUI + Inbuilt MYSL,PERL,PYTHON,OPEN OFFICE, Mozilla firefox. ->Linux Source code is open. Ex: of linux fl: Redhat,fedora, gentoo,ubuntu, slakeware,mandrivalinux, ` ` cent os,open SUSE,OEL(oracle Enterprise Lin ux) etc., Unix Architecture: Kernel:- It is combination if device drivers and sy stgem call It is heart of OS. It can understand only binary code.

description

Unix Basics

Transcript of unix.pdf

Page 1: unix.pdf

Importance of unix:

1) Unix is virous free os, so high security for data.2) Unis is stable os, it can run continuously with same performance.3) Admi., cost is less for unix servers4) Unix source code is open.ANy one can modify the source code of unix.

flavor of unix: operationg system developed based on unix source code.

Ex: Linux, solaris, Hp-UX, IBM-AIX,MACosx,sco unix etc.,

fl= core unix comds + fl commands + designed for different H/w.

Linux = unix + GUI + Inbuilt MYSL,PERL,PYTHON,OPEN OFFICE, Mozilla firefox.

->Linux Source code is open.

Ex: of linux fl: Redhat,fedora, gentoo,ubuntu, slakeware,mandrivalinux,

` ` cent os,open SUSE,OEL(oracle Enterprise Linux) etc.,

Unix Architecture:

Kernel:- It is combination if device drivers and systgem call It is heart of OS. It can understand only binary code.

Page 2: unix.pdf

All unix commands are executed by Kernel.

Kernel perform following tasks:

i) Processor managment ii) Process management iii) Memory management iv) user managment v) time sharing between users.

Shell:- It acts as interface between user and kernel. if command given by user available in unix, it convert the request into kernel understandable formant and send it to kernel for execution.

->Invalid commands are terminated by shell.

Shell in unix:

1) sh (Bourne shell)2) bash (Bourne again shell)3) ksh (korn shell)4) csh (cshell)5) tcsh(tcshell)6) zsh(zshell)

Default shells in different os

SHELL OS------ --- sh HP-UNIx,SCO-UNIx,SOLARIS

bsah LINUX,MAC-OSx ksh IBM-AIX

Page 3: unix.pdf

csh IRIX Silocon graphics

Note: Default shell can be changed temporarly or perminantly.

Files in Unix:

All unix files are classified into three types:

1) Regular or Ordinary file

2) Directory file

3) device file

1) Regular files:

i) Text file:- It contains all printable chr.,

EX: shell scripts, perl scripts etc.,

ii) Binary file:- It contains printable and unprintable characters.

ex: Unix commands, Video files, Image files etc.

2) Directory file:- It contains name and inode number of files and sub dir.,

3) Device files:- Every device is treated as a files all the device related files comes under t

Page 4: unix.pdf

his category.

Types of device files:

i) character special file: Ex: Key board,monitor,printer etc.

ii) Block special file: Ex: Hard Disk.

Structre of Unix file system:

->Unix file system begins with main directory ` called root(/). ->File system organized in inverted tree format and Hierarchical format.

->No directory created above the root(/)

/(root) | ------------------------------------------------ | | | | | | | bin etc dev temp usr home opt | ------------- | | yash oracle | ---------- | | abc def

/bin-> All unix commands are available in this dire

Page 5: unix.pdf

ctroy. Shell check for commands in this directory only.

/etc -> It contains system configuration files and files related system admin..

/dev -> All the device files are available under this directory.

/tmp-> It contains temporary files created by unix of sys admin.

/usr ->All users default directories are available in this directroy in unix o.s

/home -> All the users default directries are available in this directroy in Linux or Solaris.

/opt -> It contains optional files and subdirectories related to othird party s/w like oracle, java etc.,

Prompts In unix:

1) #

2) $

Users in unix:

1) root (system administrator login)(prompt is #)

2) Normal User login.(prompt is $).

Page 6: unix.pdf

Basic Unix Commands:

$clear -> to clear the screen

$uname ->display OS name

$uname -r -> Display the os kernel release number.

$hostname -i ->display serverIP address

$hostname ->Display servername

$uptime ->display serverside time,how log serverup and running no. of users connected to server and average load on server.

$tty ->Display terminal file name$logname (or) whoami ->display connected username.

$pwd ->display current working directory of user.

$who am i

o/p: yash pts/1 2012-06-02 19:12 (192.168.100.2)

$echo $HOME ->Display default or parent directory of user.

$echo $0(zero) ->display the current shell

$echo $SHELL ->Display the parent or default shell of user.

$date ->server date and time will be displayed

$cal ->display current month cal.,

$cal 12 2012 ->display Dec-2012 cal

Page 7: unix.pdf

$cal 2013 ->display 2013 cal from Jan to dec.,

$who (or) finger ->display all the users connected to server.

$w ->output similar to who and uptime outputs.

$ls ->display all files and sub., in current directory.

$id ->display userid,groupid and all the groups of user.

$groups ->display all the groups of user.

Working with files:-

touch:- It is used to create file(s) without data. ->file(s) created with zero bytes or zero blocks size.

$touch f1

$touch f2 f3

$ls -s ->display all files and sub dire., with sizes in blocks.

cat:-It is used to create file with data or display data from existing file(s).

$cat>file1...........................................type ctrl+d -->to come out from the file

Page 8: unix.pdf

$cat file1 ->Display data from file1. or cat<file1

$cat>file1 -> Overwrite the data in file1................ctrl+d ->to come out from the file

$cat file1

$cat>>file1 -> new data vertically appended to data in file1.....................ctrl+d

$cat file1

$cat>f1This is f1

$cat>f2This is f2

$cat f1 f2 ->f2 data verticallly appeneded to f1 data in output.

$cat f1 f2>f3 ->f1,f2 data copied to f3

$cat f1 f2>>f3 ->f1,f2 data vertically appened to data in f3

$nl file1 ->data in file1 displayed with serial numbers.

$cat -n file1 -> .......................

Page 9: unix.pdf

Creating Hidden files:

$ls -a ->display all the files and subdirectories along with hidden files from current working directory. -> Hidden files names begins with '.'

$touch .ff5 -> Hidden file .ff5 created without data.

$cat>.myfile ->Hidden file .myfile created with data......................,.........ctrl+d ->to comeout from file

$cat<.myfile ->display data from the hidden file

Copy data from one file to another file:

Syntax:

cp [-i] <sourcefile> <targetfile>

$cp file1 file2 ->file1 data copied to file2

$cp -i f1 file2

cp: overwrite file2? yes ->overwrite No ->Data not copied

$cp f1 file2 ->f1 data copied to file2

Page 10: unix.pdf

Renaming file:

Syntax:

mv <oldfilename> <newfilename>

$mv file1 file5 ->file1 renamed to file5.

$mv f1 ff6 ->f1 renamed to ff6.

$mv .ff5 ff5 ->Hiddren file .ff5 renamed

to ff5.

$mv ff5 .newfile ->ff5 renamed to hidden file .newfile.

Removing file(s):

Syntax:

rm file(s)

$rm f1 ->f1 file deleted

$rm f2 f3 ->f2,f3 files are deleted

$rm * ->delete all files in Current working directory.

Working with directories:

1) Creating Directory:

Syntax:

mkdir <directory_name(s)>

Page 11: unix.pdf

$pwd/home/oracle$rm -rf * ->Remove all files and sub direc., in current working dir.,$mkdir abc$mkdir abc/a1 abc/a1/a2$mkdir -p a/b/c/d ->-p for nested direc.,$tree abc

$tree a

2) changing the directory:

Syntax:

cd <directory_name>;

$pwd/home/oracle$cd abc ->director changed to abc.$pwd/home/oracle/abc

$cd a1/a2 ->directroy changed to a2$pwd/home/oracle/abc/a1/a2

$cd .. ->To move one dire level back or up

$pwd/home/oracle/abc/a1

$cd ../.. ->to move two dire levels back or up

$pwd

/home/oracle$cd abc/a1/a2$pwd/home/oracle/abc/a1/a2

Page 12: unix.pdf

$cd (or) cd ~ (or) cd $HOME ->to go back to user default directory i.e /home/oracle from current directory.$pwd/home/oracle

$cd / ->to go to root(/) directory.$pwd/$cd bin ->to go to bin directory.$pwd/bin$cd ->to go back to user default directory.$pwd/home/oracle

Copy file(S) into directory:

Syntax:

cp file(s) <directory>

Copy one directory contents into another directory:

Syntax:

cp -R <source_dir> <target_dir>

$pwd/home/oracle$touch f1 f2$cp f1 f2 abc ->f1,f2 files copied to abc dire.,

$cp f1 f2 abc/a1/a2 ->f1,f2 files copied to a2 directory.

$tree abc ->display all files and subdire., abc dire.,

Page 13: unix.pdf

$cp -R abc test ->all contents in abc are coped to test directroy.

Renaming the directory:

Syntax:

mv <old_dir_name> <new_dir_name>

$pwd/home/oracle$mv abc cba ->abc renamed to cba.

Removing the Directory:

Syntax:

rmdir <dir_name>

->Valid only when directory is empty. rm -r[f] <dir_name> ->valid even dire., is not empty. rm -rf * -> All files and subdir in current working dir are deleted.

$pwd/home/oracle$rmdir testerror since dire., not empty

$rm -rf test ->test directory deleted.

$rm -rf * ->All files and sub direc in c.w.d are deleted

/

Page 14: unix.pdf

| home | oracle | ------------------------ | | abc xyz | | ----------------- -------------- | | | | a1 a2 x1 x2 | ---------------- | | a11 a12 | ---------------- | | | | s1 s2 file1 test

$pwd/home/oracle$mkdir abc xyz abc/a1 abc/a2 xyz/x1 xyz/x2 abc/a1/a11 abc/a1/a12

$cd abc/a1/a11$pwd/home/oracle/abc/a1/a11$touch s1 s2 file1$mkdir test

$cp file1 /home/oracle/xyz/x1

Page 15: unix.pdf

->file1 copied to x1 directory. ->path mentioned from / directory is called absolute path.$pwd/home/oracle/abc/a1/a11$cp * test ->all files in a11 copied to test directory.

$cp * .. ->all files in a11 copied to one dire. level back i.e to a1 directory.$cp * $HOME ->all files in a11 copied to user default directory i.e to /home/oracle.$touch newfile$cp newfile ~/oldfile ->newfile in a11 copied to user default directory (oracle) and rename to oldfile.$cd$pwd/home/oracle$cp abc/a1/a11/file1 xyz/x2 ->file1 in a11 copied to ` x2 directory.

Absolute Path:-Path mentioned from root(/) directory is called absolute path.

Relative Path:- Path mentioned with respect to a directory.

create three files with data as shown below:

file1 file2 file3----- ----- ----abc abc abcdef def def123 xyz 123

cmp:- Used to compre two files.

Page 16: unix.pdf

->if files are same no output displayed otherwise it will report the line number from which difference started.

$cmp file1 file3

No output since files are same

$cmp file1 file2

cmp:file1 file2 differ in line 3

diff:- It will report which lines as to be changed

or deleted to make two different files as similar files.

$diff file1 file23c3 ->Third line first files should be<123 changed as third line of second file----- to make them similar.<xyz

Comm:- It is used to display common lines of two diffeent files. output contains three columns. -> first column contains line belongs to first file -> Second column contains line belongs to second file

-> third column contains line common of both the files.

$comm file1 file2

abc def

Page 17: unix.pdf

123 xyz

$comm -1 file1 file2 ->line belongs to first file(file1) not displayed in above output.

$comm -2 file1 file2 -> Lines belongs to second file(file2) not displayed in the above output.

$comm -12 file1 file2abc ->Display lines common to both the filesdef

tr -> used to transalate characters in file -> Change displayed in the output only.

$tr a A<file1Abc a->Adef123

$tr aei AEI<file1Abc a->AdEf e->E123 i->I

$tr [a-z] [A-Z]<file1 ->lower character in files translated to upper case characters in output .

wc-> It will count lines,words and character in given file.

$wc -l file1 ->Display number of lines in file1

$wc -w file1 ->Display number of words in file1

Page 18: unix.pdf

$wc -c file1 ->Display number of characters in file1

$wc -lc file1 ->Display no. of lines and characters in file1.

$wc -lw file1 ->Display no. of lines and words in file1

$wc -wc file1 ->Display no. of words and characters in file1

$wc file1 ->Display no. of line,words and characters in file1

Pipe(|) -> used to combine the two unix commands -> Left side command output passed as input to right side command.

Syntax:

command1|command2 =command2 (output of command1).

-> Command2 will acts on command1 output.

$cat file1|wc -l ->Display no. of lines in files1

$cat file1|wc ->Display no. of lines,words and characters in file1.$who|wc -l ->Display no. of users connected to server.

Page 19: unix.pdf

tee -> It will copy the displayed output into one or more than one file.

$date|tee d1 -> output of date is copied to d1 file

$date|tee d1 d2 d3 d4 d5 ->output of date is copied to d1,d2,d3,d4 and d5 files.

$who|wc -l|tee ucnt ->output of who|wc -l copied to ucnt file.

Vi Editor

$cat>file1.........................................................................ctrl+d -> to come out from the file

$vi file1 -> file1 opened in vi editor in the command mode.................................................................

Vi editor has three modes

1) command mode 2) Insert mode or input text mode 3) Ex command or colon mode

Page 20: unix.pdf

1) Command mode:-It is the default mode of editor. -> In this mode, each characater typed on keyboard acts like command.

2) Insert mode:- This mode permits to add,modify and append new text to existing text.

3) Ex command mode or Colon Mode:- Last line of vi editor is called command line. Commands can be executed in this mode.

Changing from command mode to insert mode:

i ->Command mode changed to insert mode without changing the position of cursor.ESC -> To switch from insert mode(IM) to Command Mode(CM)

I -> CM changed to IM and cursor moves to beginning of line.

a -> CM changed to IM and cursor moves towards right by one char.

A -> CM changed to IM and cursor moves to end of line

o -> CM changed to IM and newline created below the cursor position.O -> CM changed to IM and new line created above the cursor position.

Page 21: unix.pdf

Command Mode Commands:

l ->cursor moves towards right by one characater.

5l -> Cursor moves towards right by 5 characters.

h -> cursor moves towards left by one character.

5h -> cursor moves towards left by 5 characters.

$ -> cursor moves to last character of line.*

^ or 0(zero)-> Cursor moves to beginning of line *

w -> cursor moves towards right to the first character of next word5w -> cursor moves towards right to the first character of 5th wordb -> cursor moves towards left to be the first characater of previous word.e -> cursor moves the end of word.

j -> cursor moves down to next line without changing the column.

k-> Cursor moves up to previous line without changing the column.

J or 2J ->Join two Lines.

L -> cursor moves to end of current page.

H -> cursor moves to beginning of current page.

G -> cursor moves to end of file

gg ->cursor moves to beginning of file

Page 22: unix.pdf

15G ->cursor moves to 15th line of file.

u -> undo the changes

x or dl -> delete a character from the cursor position.

5dl or 5x ->Delete 5 characters from cursor postion towards right.

dw -> delete a word

5dw -> delete five words towards right.

dd -> delete a line

5dd -> delete five lines in down.

X ->Delete previous charater from curor positionD ->Delete all the characters from cursor position to end of line

dL -> delete all the lines from cursor position to end of current page.

dH -> delete all the lines from cursor position to beginning of current page.

dG -> delete all the lines from cursor position to end of file

dgg -> delete all the lines from cursor position to beginning of file.

yl-> copy a character from cursor position.

Page 23: unix.pdf

p -> paste the copied data.

5yl -> copy five character from cursor position towards right.

yw -> copy a word.

5yw -> copy five words towards right.

yy -> copy a line

5yy -> copy 5 lines in down

yL -> copy all the lines from cursor position to end of current page.yH -> Copy all the lines from cursor position to beginning current page.yG -> copy all the lines from cursor position to end of file.

ygg -> copy all the lines from cursor position to beginning of file.

cl -> CM changes to insert mode and delete a character from the cursor postion.cw -> CM changed to IM and delete a word

cc -> CM changes to IM and delete a line.

colon Mode:

-> to get colon(:), Hold the shift key and type : ; key in command mode.

Page 24: unix.pdf

:set nu -> assign serial no. for all the lines in file.*

:set nonu -> Remove the assigned serial numbers.*

:3 -> cursor moves to third line of file

:2d -> delete second line

:4,8d -> delete 4 to 8 lines in file.

:!date -> Date command executed.

:!pwd -> disply current working directory of user.

:!<command> -> Given command executed.*

:2,6 w ff9 -> 2 to 6 lines in editor copied to ff9 file.*

:8,10 w>>ff9 ->8,10 lines in editor appened to data in ff9 file.

Exit from Vi editor:

:q -> To close the opened file

:q! -> To close file without save the changes.

:w -> Save changes whithout closing the file

:e! -> Ignore Changes without closing the file

:wq -> Save changes and exit from the file

:wq! -> Save changes and exit from the read only mode file

Encrypting the file in Vi editor:-

Page 25: unix.pdf

$vi -x newfile

Enter encryption Key: visix

Re-enter same key:visix

->enter data into file and save and exit

$vi newfile

Enter Encryption Key: ->if wrong key provided data displayed in unreadable format.

$man vi ->Manual help of vi command is displayed.

$man <command> -> Manual help of given command is displayed.

Meta Characters:

* -> matches zero or more characters

? -> Matches single character

- -> matches characater in range

[.....] -> matches characters in list

[!.....] -> matches characters other than the characters in list

Examples:

Page 26: unix.pdf

$ls f* -> Display the files begins with f

$ls f*m -> Display the files begins with f end with m

$ls f??m -> Display the files containing four characters first character should be f and fourth character should be m.

$ls *.* -> files containing . extension

$ls *.?? -> Display files containing two characters in the .extension.

$ls [0-9]* -> Display the files begins with digit.

$ls [aeiou]* -> Display the files begins with lower case vowels

$ls [a-c]* ->Display the files begins with any characater from a to c

$ls [!a-z]* -> Display all the files except the files begins with lower case alphabet.

$ls *[0-9] -> Display the files end with digit.

Filter Commands:

head:- Used to extract lines from the beginning of file By default it will display first 10 lines

Page 27: unix.pdf

$head file1 -> Display first 10 lines from file1

$head -3 file1 -> Display first three lines from file1 or head -n 3 file1

tail:- Used to extract lines from the end of file default it will display last 10 lines $tail file1 -> Display last 10 lines from file1

$tail -4 file1 -> Display last 4 lines from file1 or tail -n 4 file1

$tail -f file1 -> file1 opened in growth monitoring mode.

$tail +5 file1 -> display all the lines from 5th line to end of file.

$head -5 file1|tail +5 -> Display only 5th line from file1

cut:- It is used to extract fields or characters from the given file. It will recognise the fields if the field

separator is tab.

create emp file:

100 smith clerk 800200 allen analyst 1600300 ward manager 2000

Page 28: unix.pdf

->Tab is field separator

$cut -f 1,3 emp -> Display 1st and 3rd fields from emp

$cut -f 2-4 emp -> Display 2nd,3rd,4th fields from emp

$cut -c 1-3 emp -> Display 1-3 characters from emp file.

$cut -c 1-5 emp -> Display 1-5 characters from emp file tab is also recognised as one character.

$tr '\t' ':'<emp>emp1 ->Tab space in emp file replaced with : and result is stored in emp1 file

$cut -f 1,3 -d':' emp1 -> Display 1st and 3rd fields data from emp1 file -d option should be used to specify the field separator if field separator is other than tab space

paste:- It will join the two files horizontally. -d option should be used to specify the required filed separator.

$cut -f 1-2 -d':' emp1>emp2$cut -f 3-4 -d':' emp1>emp3

Page 29: unix.pdf

$paste emp2 emp3100:smith clerk:800200:allen analyst:1600300:ward manager:3000

$paste -d':' emp2 emp3100:smith:clerk:800200:allen:analyst:1600300:ward:manager:3000

Character ASCII value 0 48 1 49 . . A 65 B 66 . . a 97 b 98 . .

sort:- It is used to sort the data in file. It will sort the data based on ASCII values. Default order is ascending order.

$cat>file1abcdef123xyzabcctrl+d ->to come out from file

$sort file1 -> Data in file1 sorted in output.123abcabcdef

Page 30: unix.pdf

xyz

$sort file1>file2 -> sorted data of file1 copied to file2

$sort -o rsult file1 -> sorted data of file1 copied to output file rsult.

$sort -u file1 ->Data in file1 sorted but remove the duplicates from output.

$sort -u -o result file1 -> sorted data of file1 without duplicated copied to output file result.

$sort -r file1 -> data in file1 sorted in descending order.

$sort -c file1 -> No output displayed if file1 data is sorted other wise it will report the line number from which disorder started.

Create num file with numeric data.

$sort -n num -> numeric data in num file sorted in ascending order

$sort -rn num -> Numeric data in num file sorted in descending order.

Page 31: unix.pdf

uniq:- It will remove the duplicate lines from the sorted file.

$uniq file2 -> Remove duplicate lines in output if file2 is in sorted order.

$uniq -u file2 -> Diplay the line which are not duplicated in file2.

$uniq -d file2 -> Display the lines which are duplicated.

$uniq -c file2 -> Count the lines in file2

o/p 1 123 2 abc 1 def 1 xyz

grep:- It is used to search for pattern in file(s) and print line or lines containing pattern

Syntax:

grep [option] <pattern> file(s)

Examples:

$grep unix file1 -> Display lines containing unix pattern from file1

$grep unix file1 file2 -> Display the lines containing unix

Page 32: unix.pdf

pattern from file1,file2

$grep unix * -> Display lines containing unix pattern from all files in current working direcotry.

Options with grep:

1) ignoring the case(-i):-

$grep -i unix file1 -> Display all lines containing unix pattern irrespective of case of unix from file1.

2) Deleting the lines(-v):

$grep -v unix file1 ->Display all the lines except unix pattern lines from file1.

$grep -iv unix file1 ->Display all the lines except unix pattern lines from file1 irrespective of case of unix.

003) Lines with line numbers(-n):

$grep -n unix file1 -> Display lines with line numbers containing unix pattern.

$grep -in unix file1 -> Display lines with line numbers containing unix irrespective of case of unix from file1.

Page 33: unix.pdf

$grep -vn unix file1 -> Display lines with line numbers except unix pattern lines from file1

$grep -ivn unix file1 -> Display lines with line numbers except unix pattern lines irrespective of case of unix from file1.

4) Counting lines(-c):

$grep -c unix file1 ->count unix pattern lines from file1

$grep -vc unix file1 ->count all lines except unix pattern lines from file1

$grep -ic unix file1 ->count all the unix pattern lines from file1 irrespective of case of unix.

5) Searching for multiple patterns(-e):

$grep -e unix -e oracle file1 -> Display unix as well as oracle pattern lines from file1.$grep -E 'unix|oracle' file1

6) Exact match(-w):

$grep -w oracle file1 -> Display the lines exactly matched with oracle pattern from file1.

^ ->matches at the beginning of line

Page 34: unix.pdf

$ -> matches at the end of line ^$ -> Blank lines

$grep ^s file1 -> Display the lines begins with s from file1

$grep ^[aeiou] file1 -> Display the lines begins with lower case vowel.

$grep ^[0-9] file1 -> Display the lines begins with digit from file1$grep x$ file1 -> Display the lines end with x from file1.$grep [0-9]$ file1 -> Diplay lines end with digit

from file1.

$grep ^$ file1 ->Display the blank lines from file1

$grep -v ^$ file1 -> Display all the lines except blank lines from file1

$grep -v ^$ file1>file2 -> All lines except blank lines in file1 copied to file2

$grep ^unix file1 -> Display lines begins with unix from file1.

Regular Expression:- Any simple pattern with meta characters

Page 35: unix.pdf

is called a regular expression.

fgrep(faster grep): It is used to search for simple patterns. Regular expressions are not valid in fgrep.

$fgrep unix file1 -> unix pattern lines are displayed from file1.

$fgrep 'unix>linux' file1 -> unix as well as linux pattern lines are displayed from file1.

egrep(extended grep):-It is used to search for simple patterns and regular expressions.

$egrep unix file1 -> unix pattern lines are displayed from file1.

$egrep ^s file1 -> Display the lines begins with s

$egrep 'unix|oracle' file1 -> Display unix, oracle pattern lines from file1

Sed(stream editor):- It is multi purpose filter command.

$sed 3q file1 -> Display first three lines from file1.

Page 36: unix.pdf

q-> quit

$sed -n 2,5p file1 -> display 2 to 5 lines from file1. p-> print

$sed -n '2,5p>8,10p' file1 -> Display 2 to 5 and 8 to 10 lines from file1$sed -n 8,8p file1 ->Display 8 line from file1

$sed -n '$p' file1 -> Display last line from file1

$sed -n /unix/p file1 -> unix pattern lines are printed from file1$sed -n '/unix/p>/oracle/p' file1 -> unix, oracle pattern lines are are printed from file1

$sed -n '/unix/w ff1' file1 -> unix pattern lines in file1 copied to ff1 file. w-> write$sed -n '/unix/w ff2>/oracle/w ff3' file1 ->unix patter lines copied to ff2,oracle pattern lines copied to ff3 from file1

Replacing a string with another string using sed:

Syntax:

sed s/searchingstring/replacingstring/[i][g] file(s)

s-> Substitute i -> Ignoring the case

Page 37: unix.pdf

g -> Globally i.e., duplicates in line(s).

$sed s/unix/ORACLE/ file1 -> unix in file1 replaced with ORACLE in output.

$sed s/unix/ORACLE/i file1 -> unix in file1 replaced with ORACLE irrespective of case of unix in output.$sed s/unix/ORACLE/g file1 -> unix in file1 replaced with ORACLE including duplicates in line(s).

Creating users:- root user only can create users.

Syntax:

useradd <username>

Assigning password to the user:

Syntax:

passwd <username>

Note: At the time of creating user if root will not specify any group, unix on its own create a group, group name is also same as username. This group is called 'user private group schema'.

-> All valid users information available in /etc/passwd file.

#useradd usr5#passwd usr5

Page 38: unix.pdf

New unix password:usr5Enter same password again:usr5

Connect to usr5 user.

$lognameo/p: usr5$pwdo/p: /home/usr5$id

$grep -w usr5 /etc/passwd

/*Disconnect from the user.*/

Deleting the User:

Syntax:

userdel -r <username>

#userdel -r usr5

Creating Groups:

Syntax: groupadd <group_Name>

#groupadd g1#groupadd g2Creating User with groups:

Syntax-1:

useradd -g <primary_groupname> <username>;

usermod -G <secondary_group> <username>;

Syntax-2

Page 39: unix.pdf

useradd -g <primary_group> -G <secondary_group> <username>;

#useradd -g g1 usr88#usermod -G g2 usr88

->Assign password to the user.

#useradd -g g1 -G g2 usr99

->Assign password to the user:

Note:-Primary groups information available in /etc/passwd file secondary groups information available in /etc/group file.

$lognameusr88$pwd/home/usr88$id

$group

$grep -w usr88 /etc/passwd

$grep -w usr88 /etc/group

#userdel -r usr88#userdel -r usr99

#groupdel g1#groupdel g2

Deleting the groups:

Syntax:

Page 40: unix.pdf

groupdel <group_name>;

--------------------------- | | | g1 g2 g3 | --------- | | | u1 u2 u3 | file1

Every File will have three category of users

1) owner(u) 2) group(g) 3) others(o)

1) owner(u):- user who created file

2) group(g):- All the users belongs to owner group

3) others(o):- All the users belongs to other groups (other than owner group).

Owner for file1 -> u1

Group members for file1 -> u2,u3

Others for file1 ->g2,g3 groups users.Every file will have three types of permissions:

1) read(r) 2) write(w) 3) execute(x)->Without Read permissions file cannot be opened

Page 41: unix.pdf

-> Without wirte permission file cannot be modified

-> Without executable permission, file cannot be executed.

Note:- Only owner can change the file permissions.

Working with file permissions:-

$rm -rf *$pwd/home/yash$ls$umask 0022$touch f1$ls -l f1 ->file info., displayed in long list format output contains 8 fields

-rw-r--r-- 1 yash yash 0 Jun 4 16:27 f1

Filed Description

1 Filetype

2 File permissions

3 Filesystem link

4 owner

5 Group

6 Size of file in bytes

7 Date and time of creation

8 File name

Page 42: unix.pdf

Different File types:

1) regular file(-)2) Directory file(d)3) characater special file(c)4) block special file(b)5) link file(l)

$ls -l f1-rw-r--r-- .............. f1

Changing file permissions:- Only owner can change the file permissions. ->'chmod' command is used to change existing file permissions.

Syntax:

chmod who[+/-/=] permissions file(s)

Who:

Owner(u)group(g)others(o)

Permissions:read(r)write(w)execute(x)

+ ->Add permission

- -> remove the permission

= -> Remove the existing permissions and

Page 43: unix.pdf

assign the new permissions.

?Add write permission to group on f1

$chmod g+w f1

$ls -l f1-rw-rw-r-- ...........f1

?Add executable permission to owner and others on f1

$chmod uo+x f1

$ls -l f1-rwxrw-r-x ..........f1

?Remove Write permission from owner on f1.

$chmod u-w f1

$ls -l f1-r-xrw-r-x.............f1

?Assign only Executable permission to group on f1.

$chmod g=x f1

$ls -l f1-r-x--xr-x...........f1

Weightages for file permissions in numeric method:

1) read(r)->42) write(w)->23) execute(x)->14) read,write(rw)->65) read,execute(rx)->5

Page 44: unix.pdf

6) write,execute(wx)->37) read,write,execute(rwx)->7

Changing existing file permissions in numeric method:

Syntax:

chmod n1n2n3 file(s)

$umask0022$touch f5$ls -l f5-rw-r--r-- ..............f5

?Assign following permission on f5

owner->r,w,x group->wx other->x$chmod 731 f5

$ls -l f5-rwx-wx--x ..........f5

?Assign following permission on f5

owner->x group->w other->rx

$chmod 125 f5

$ls -l f5---x-w-r-x ............f5

?Assign read,write and executable permissions on f5

Page 45: unix.pdf

for owner, group and others.

$chmod 777 f5

$ls -l f5-rwxrwxrwx .............f5$lognameyash$pwd/home/yash$rm -rf *$umask 0000$umask 0000$touch f6$mkdir abc$ls -l -rw-rw-rw-.......f6drwxrwxrwx.......abc

If umask value changed file permisions are also changing, from this we observerd there is adependency between umask and file permissions.

umask(user creation mask):-

->By default unix will allocate rw-rw-rw-(666) permission for file and rwxrwxrwx(777) for directory.

->permissions displayed in ls -l output depends on umask value i.e, umask value substracted from standard permissions and remaining permissions are displayed.

umask 0022

Page 46: unix.pdf

1st zero indicates Numeric Notation.

2nd digit(ex., zero) indicates, Permissions to be substracted from default owner permissions.

3rd digit(ex., 2) indicates, Permissions to be substracted from default group permissions.

4th digit(ex., 2) indicates, Permissions to be substracted from default others permissions.

$umask 0022 $umask0022$touch f1 ->permisions allocated are(666)

$ls -l f1-rw-r--r-- ....f1 666 022 ---- 644

$umask 0000$umask0000$touch f5 ->permissions allocated are(666)$mkdir abc -> (777)

$ls -l 666 777-rw-rw-rw- f5 000 000drwxrwxrwx abc --- --- 666 777

Page 47: unix.pdf

$umask 0222$touch ff1 (666)$ls -l ff1 666-r--r--r-- 222 ----- 444

Chaging ownership of file:- root user only can change the ownership of file.

Syntax:

chown <newowner> file(s)

Chnaging group of file:- root user only can change group of file

Syntax:

chgrp <newgroup> file(s)

# ls -l /home/yash/file1

-rw-rw-rw- 1 yash yash 0 Feb 2 21:24 /home/yash/file1

#chown oracle /home/yash/file1

# ls -l /home/yash/file1

-rw-rw-rw- 1 oracle yash 0 Feb 2 21:24 /home/yash/file1

# chgrp oracle /home/yash/file1

# ls -l /home/yash/file1

Page 48: unix.pdf

-rw-rw-rw- 1 oracle oracle 0 Feb 2 21:24 /home/yash/file1

su:- This command is used to change from one login to another login.

$lognameyash$whoamiyash$pwd/home/yash$su - oraclePassword: $lognameyash$whoamioracle$pwd/home/oracle$exit ->To comeout from oracle login$lognameyash$whoamiyash

Shells in UNIX:

1) Bourne shell(sh):- It is developed by Stephen Bourne

Page 49: unix.pdf

User prompt: $ root prompt: # It is default in Hp-Ux,Solaris,SCO UNIx

2) Bourne Again shell(bash):- It is developed by Brain Fox User prompt: $ root prompt: # It is default in Linux,MAC OS X3) Korn Shell(ksh):-It is developed by David Korn Userprompt: $ root prompt: # it is default in IBM-AIX

4) Cshell (csh):- It is Developed by Bill Joy User prompt: % root prompt: # It is default in :IRIX Silocon Graphics

Changing Shell:-

$lognameyash$echo $SHELL -> Display the default( or parent) Shell/bin/bash$echo $0 -> Display the current shell-bash

$ksh -> To go to child shell korn shell

$echo $SHELL -> Display the parent shell/bin/bash$echo $0ksh$exit -> to come out from the ksh

$echo $SHELL

Page 50: unix.pdf

/bin/bash$echo $0-bash

Executing more than one unix command at a time;

$logname;pwd;date

SHELL SCRIPTING

-> A file that contains collection of unix commands. ->Default execution is sequential.

->It supports conditional statements to execute

the commands conditionally. -> It supports loops to execute the commands required no. of times. -> Shell scripts are end with .sh extension, that is optional.

->'echo' is used to display message or value in

variables -> 'read' is used to read values into variables.

?Write a Shell script to display messages.

$pwd/home/oracle$vi welcm.shecho This is unix Shell scriptingecho This is first class of shell

Page 51: unix.pdf

:wq

Executing shell script:

$sh welcm.sh

?WAs to execute unix commands$vi cmdsdatelognamepwdcal:wq

$sh cmds

Variable:- It is an integral part of program. -> It is used to hold the data temporaryly.

Rules for naming the varibale

-> variable name should begins with alphabet or underscore(_). ->valid characters are i) A-Z ii) a-z iii) 0-9 iv) underscore(-)

->Variable name is case sensitive

All the unix variables are classified into two types:

1) User defined varibales2) Unix defined or system defined or Environment varibales.

1) User defined variables: Variables defined by use

Page 52: unix.pdf

r. These are classified into three types.

i) Local Variables ii) constant variables iii) global variables

i) Local Variables:- Variable declared in parent shell valid in parent but not valid in other child shells$echo $SHELL/bin/bash$echo $0-bash$a=10$echo $a ->display value in variable.10$b=50$echo $b50$b=70$echo $b70$sh ->To go to child shell$echo $SHELL/bin/bash$echo $0sh$echo $a ->no output displayed since a is local variable

$exit ->to come out from sh

$echo $0-bash$set ->display all the declared variables with values.

$v=manager$echo $v

Page 53: unix.pdf

manager

.bashrc:- This hidden file available in every user login. To make any variable as perminant variable,

variable should be declared in this file.

$pwd/home/oracle$vi .bashrc

x=300y=400

:wq

$. .bashrc ->executing the file.

$echo $x300$echo $y400

Note: This file is automatically executed when user loggedin.

ii) constant variables:- 'readonly' key word is used to declare constatnt variables.

->values of these variables cannot be changed. -> These are also local variables.

$k=400$echo $k400$k=500$echo $k

Page 54: unix.pdf

500$readonly k$k=600Error since k is read only variable.$echo $k500

$readonly r=500$echo $r500$r=5error since r is readonly variable.

$readonly ->Display all the readonly variables.

iii) Global varibales:- variable declared in parent shell valid in parent shell as well as other child shells. ->'export' key word is required to declare global variable.

$echo $SHELL/bin/bash$echo $0-bash$lv=400$export g=500$echo $lv400$echo $g500$ksh$echo $SHELL/bin/bash$echo $0ksh$echo $lv ->no value displayed since lv is local variable

$echo $g500 ->since it is globall variable.

Page 55: unix.pdf

$exit$echo $0-bash

.bash_profile:- This hidden file available in every user login. -> If any third party software (ex. oracle,teradata,apps etc.,) is running in linux, class path of s/w i.e where third party s/w is installed and where the third party s/w executables are availbe should be mentioned in this file, then only user can access third party s/w.

-> This file and .bashrc are automatically executed when user logged in.

$vi .bash_profile

2) Environment Variables:- Variables defined by unix. ->Unix use these variables to set the environment of user.

$set --> Display all the env. variables with default values.

..............

...............

...............

HOME=/home/yash ->specifies the default dir of visix user.

Page 56: unix.pdf

PS1='$' -> specifies the default prompt.PS2='>' -> specifies the next line symbol.

SHELL=/bin/bash -> It specifies the default shell of user........................

Note:- To change the value of any environment variable value perminantly its value should be changed in .bash_profile file.

$lognameyash$echo $HOME/home/yash$echo $PS2>$echo $SHELL/bin/bash

Changing the prompt:-

$vi .bash_profile............................

export PS1=?....................................:wq

$. . bash_profile ->executing the file.

? ->$ prompt changed to ?.

Page 57: unix.pdf

?WAS to read values in to variables and display the values.

$vi vardataecho enter two valuesread a becho values are $a and $b

:wq

$sh vardata

?WAS to remove blank lines from given file

$vi blankecho enter filenameread fgrep -v ^$ $f>tempmv temp $fecho blank lines deleted:wq

Operator in Unix:

1) Arithmetic operators:- These are used to perform

arithmetic operations.

+ ->addition

- -> sub

\* ->multiplication

/ ->division

% ->Modular division

2) Numeric Comparison Operators:-

Page 58: unix.pdf

1) -gt ->Greater than

2) -ge -> Greater than or equal to

3) -lt -> Less than

4) -le -> Less than or equal to

5) -eq -> equal to

6) -ne -> Not equal to

3) Logical Operators:- These are used to combine the results of more than one expression to get single result.

1) -a -> AND

2) -o -> OR

3) ! -> Not

Note:-'expr' Keyword should be used to perform arithmetic operation between two integer values.

$a=10$b=20$expr $a + $b ->before and after + space is compulsory.o/p:30

$c=`expr $a + $b`$echo $co/p: 30Note: expr can be replaced with 'let'

$let d=a+b$echo $do/p:30

Page 59: unix.pdf

$echo $a+$b10+20$c=`echo $a+$b|bc` `->back quote$echo $co/p:30

?WAS to find sum and difference of two integers values

$vi sumdifecho enter two integersread a bc=`expr $a + $b`echo a+b=$cc=`expr $a - $b`echo a-b=$c:wq

Note:Above program valid only for integers but not valid for float values.

?WAS to find sum,difference and product of two integers and floats.

$vi arth

echo enter two valuesread a bc=`echo $a+$b|bc`echo a+b=$cc=`echo $a-$b|bc`echo a-b=$cc=`echo $a\*$b|bc`echo a*b=$c

:wq

Conditional Statements:- These are used to execute the

Page 60: unix.pdf

statements conditionally.

1) Simple if:

if [ Condition ] then .............. ................ fi

-> Given condition true then statements under if are are executed.

2) if-then-else

Syntax: if [ condition ] then ........... ........... ...........

else .......... ......... fi

->Given condition true, then statements under if are executed, otherwise statements under else are executed.

3) Ladder if:- Used to check multiple conditions.

Syntax:

if [cond1 ] then ........ ........ elif [ cond2 ]

Page 61: unix.pdf

then ........... ............ elif [cond3 ] then .......... .........

else ......... ......... fi

-> If all the conditions are failed, then statements under else are executed.

4) nested if:- If statement in another if statement.

Syntax:

if [ cond ]then ........ ........ if [cond ] then ........... ........... if [ cond ] then ........... ........... else ......... ....... fi

Page 62: unix.pdf

else ..... .... fielse............fi

Case:-

Syntax:

case <variable> in value1) ......... .........;; value2) .......... .......... ..........;; value3) ........... ........... ...........;;

[*) .............. .............;;] esac

-> value in variable is other than the mentioned values then statements under *) are executed.

?WAS to check given user connected to server or not

Page 63: unix.pdf

$vi userccheckecho enter usernameread usrif who|grep -w $usr>/dev/nullthenecho user connectedelseecho user not connected to serverfi

:wq

?WAS to check no. of users conncted to server more than one or not

$vi usrcnt

c=`who|wc -l`if [ $c -gt 1 ]thenecho No. of users connected: $celseecho you are only user to serverfi

:wq

?WAS to check give number is even or odd

$vi evenoddecho enter numberread nc=`expr $n % 2`if [ $c -eq 0 ]thenecho Given numebr evenelseecho given numebr is odd

Page 64: unix.pdf

fi :wq

?WAS to compare two given numbers:

$vi numcmp

cho enter two valuesread a bif [ $a -gt $b ]thenecho a is bigelif [ $a -lt $b ]thenecho b i bigelseecho a is equal to bfi

:wq

checking whether user valid user nor not for unix:

-> All the valid users information available in /etc/passwd file.

$grep -w visix /etc/passwd

?WAS to check given user valid or not

$vi usrchk

echo enter usernameread usrif grep -w $usr /etc/passwd>/dev/nullthen

Page 65: unix.pdf

echo Given user is validelseecho Given user is not validfi

:wq

?WAS to check given number is within the given range or not using case

$vi casetest

echo enter any value form 1 to 4read ncase $n in1) echo one;;2) echo two;;3) echo three;;4) echo four;;*) echo value is out of range;;esac

:wq:

?WAS to check given character is lower case voewl, upper case vowel or digit.

$vi casechk

echo enter any characterread chcase $ch in[aeiou]) echo lower case vowel;;[AEIOU]) echo Upper case vowel;;[0-9]) echo digit;;esac

:wq

Page 66: unix.pdf

:$v=manager$echo $v|cut -c 1-3man

?WAS to check quarter of given month using case:

$vi caseqrtrecho enter month in capsread mc=`echo $m|cut -c 1-3`case $c inJAN|FEB|MAR) echo first quarter;;APR|MAY|JUN) echo second quarter;;JUL|AUG|SEP) echo third quarter;;OCT|NOV|DEC) echo fourth quarter;;*) echo enter month in caps;;esac

:wq

?WAS to check the result of student pass mark of each subjectis more than or equal to 40

$vi stdrlstecho enter three subjects marksread m1 m2 m3if [ $m1 -ge 40 ]then if [ $m2 -ge 40 ] then if [ $m3 -ge 40 ] then echo Result:PASS else echo Result:Fail fi else echo Result:Fail fi elseecho Result:Fail

Page 67: unix.pdf

fi

:wq

?Write above program using logical and operator:

$vi resultecho enter three subjects marksread m1 m2 m3if [ $m1 -ge 40 -a $m2 -ge 40 -a $m3 -ge 40 ]thenecho result passelseecho result failfi

String Test:

1) str1 = str2 -> Returns true if both the strings are same

2) str1 != str2 -> Returns true if strings are different

3) -n str -> Returns true if string size more than zero

4) -z str -> Returns true if string is empty

File Test:

1) -e <file_name> -> Returns true if file exists

2) -s <file_name> -> Returns true if file size more than zero

3) -f <file_name> -> Returns true if file is reg file

Page 68: unix.pdf

4) -d <file_name> -> Returns true if file is directory file

5) -b <file_name> -> Returns true if file is block special file

6) -c <file_name> -> Returns true if file is character special file

7) -r <file_name> -> Returns true if file will have read per.,

8) -w <file_name> -> Returns true if file will have write per,.

9) -x <file_name> -> Returns true if file will have executable permission.10) -O <file_name>-> Returns true if your are owner for file

11) -G <file_name> -> Returns true if file belongs to your group

12) f1 -ot f2 -> Returns true if f1 is older than f2

13) f1 -nt f2 -> Retruns true if f2 is older than f1

?WAS to compare the two strings

$vi stcmpecho enter two stringsread str1 str2if [ $str1 = $str2 ]thenecho two strings are sameelseecho two different strings are enteredfi

Page 69: unix.pdf

:wq

?WAS to check give string is empty or not

$vi stchk

echo enter stringread strif [ -z $str ]thenecho Given string is emptyelseecho given string is:$strfi

:wq

Examples on File Test:

?wAS to delete a files

$vi fdelecho enter file nameread fnif [ -e $fn ]thenrm -rf $fnecho file deletedelseecho file not existsfi

:wq

?WAS to check give file is reg file dir. file or other type of file.

$vi fchk

Page 70: unix.pdf

echo enter filenameread fnif [ -e $fn ]then if [ -f $fn ] then echo given file is regular file elif [ -d $fn ] then echo give file is directory file else echo given file is not reg or dir file fielseecho file not existsfi:wq

?WAS to display data from given file if file will have read permission.

$vi fdataecho enter file nameread fnif [ -e $fn ]then if [ -f $fn ] then if [ -r $fn ] then cat $fn else echo file will not have read permission fi else echo file is not regular file fielseecho file not existsfi

Page 71: unix.pdf

:wq

?WAS to check wheter you are owner or not for given file

$vi fowner

echo enter file nameread fnif [ -e $fn ]then if [ -O $fn ] then echo your are owner for given file else echo you are not owner fielseecho file not existsfi

:wq

?wAS to check whether file belongs to your group or not

$vi fgroup

echo enter file nameread fnif [ -e $fn ]then if [ -G $fn ] then echo file belongs to your group else echo file is not in your group fielseecho file not existsfi

Page 72: unix.pdf

:wq

Checking the Disk space:

du(disk space used):- It will display the space used by file or directory in blocks.

$du file1 ->display space occupied by file1 in blocks

$du -b file1 ->display size of file in bytes

$du -s /home/oracle ->Display blocks occupied by oracle in summarized format.

df(disk free): ->display file systems information.

$df ->Display the file systems info. in kb.

$df -h ->display file systems information in MBs and GBs.

free:- It will display memory and swap information.

$free

:Loops:- These are used to execute the statements required no., of times.

1) while 2) until 3) for 4) select

1) while:

Page 73: unix.pdf

Syntax-1

while [ condition ] do ............ ............. ............. done

-> Given condition true, then statements under while are executed.

Syntax-2

while true do ........... ......... .......... done

-> Above loop is infinite loop,'break' or 'continue' statementsare used to come out from loop or to continue the loop.

2) until:

Syntax-1

until [ condition ] do ............ ............. ............. done

-> Given condition false, then statements under until are executed.

Page 74: unix.pdf

Syntax-2 until false do ........... ......... .......... done

-> Above loop is infinite loop,'break' or 'continue' statementsare used to come out from loop or to continue the loop.

?WAS to print numbers upto given number using while loop

$vi whilenum

echo enter numberread ni=1while [ $i -le $n ]doecho $ii=`expr $i + 1`done

:wq

?Write a shell script to find even numbers sum and odd numbers sum upto give number using until loop

$vi untilsum

echo enter numberread n

Page 75: unix.pdf

i=1es=0os=0until [ $i -gt $n ]do if [ `expr $i % 2` -eq 0 ] then es=`expr $i + $es` else os=`expr $i + $os` fii=`expr $i + 1`doneecho Even numbers sum:$esecho Odd numbers sum :$os

:wq

Creating user with default directory under /usr:

#useradd -d /usr/myusr -m myusr

?WAS to create given number of users but default directory of users should be under /usr directroy.

#vi whileusr

echo enter no. of users requiredread ni=1while [ $i -le $n ]doif grep -w u$i /etc/passwd>/dev/nullthenecho u$i already existselseuseradd -d /usr/u$i -m u$iecho u$i createdfii=`expr $i + 1`done

Page 76: unix.pdf

:wq

?write a shell script to check give user connected server or or if user not connected continuously check for

user until user connected to server using while loop.

$vi whileuser

echo enter usernameread usrwhile truedo if who|grep -w $usr>/dev/null then echo $usr connected break else echo cheking for user sleep 10 continue fidone

:wq

select loop:- It is menu based loop.

Syntax:

select <variable> in value1 value2 value3 ....... do ............ .............. done

-> It will form menu with given values, while executing program.

Page 77: unix.pdf

$vi slct

select i in Osname ServerIP Date Exitdocase $i inOsname) uname;;ServerIP) hostname -i;;Date) date;;Exit) exit;;*) echo enter correct choice;;esacdone

:wq

?WAS to find sum,difference and product of two integers using case

$vi slarth

echo enter two valuesread a bselect i in SUM DIF PROD EXITdocase $i inSUM) echo sum is:`expr $a + $b`;;DIF) echo differe is:`expr $a - $b`;;PROD) echo product is:`expr $a \* $b`;;EXIT) exit;;*) echo enter correct choice;;esacdone :wq

for loop:

Syntax-1

Page 78: unix.pdf

for <varibale> in const1 const2 const3 ........

do ............ ............. done

Syntax-2:

for <variable> in 'seq $n' do ......... ........ .......... .......... done

->Here n is variable

?WAS to display give four values using for loop

$vi fornum

echo enter four valuesread a b c dfor i in $a $b $c $ddoecho $idone

:wq

?WAS to find the sum of given four values

$vi forsum

echo enter four valuesread a b c d

Page 79: unix.pdf

sum=0for i in $a $b $c $ddosum=`expr $sum + $i`doneecho sum is:$sum

:wq

Create EMP file as show below:

$cat emp100:smith:clerk:800200:allen:analyst:1600300:ward:manager:3000

$cut -f 4 -d':' emp ->display 4 field data from emp file

$cat emp|cut -f 4 -d':'

?WAS to display data from emp file using for loop;

$vi foremp

for i in `cat emp`doecho $idone

:wq

?WAS to display data from emp file if sal of employee greater than or equal to 2000.

$vi forsal

Page 80: unix.pdf

for i in `cat emp`dos=`echo $i|cut -f 4 -d':'`if [ $s -ge 2000 ]thenecho $ifidone

:wq

Positional parameters or command line arguements: -> These are used to pass values to shell script from the command line at the time of executing shell script.

->positional paramters are from $1, $2, $3 etc.,

?WAS to find sum of two given numebrs using positional parameters.

$vi sum

a=$1b=$2c=`expr $a + $b`echo sum is:$c

:wq

Displaying the step by step execution of shell script

$sh -x sum

+ a=4+ b=6

Page 81: unix.pdf

++ expr 4 + 6+ c=10+ echo sum is:10sum is:10

Note:- without writing program, we can assign values to p.p at command prompt using 'set' command.

$set A B C D E F G H I J

$echo $1 ->Display first p.p valueA$echo $9 ->Display 9th p.p valueI$echo $10A0$echo ${10} ->Display 10th p.p valueJ$echo $# ->DIsplay No. of p.p involved10$$echo $* ->Display values of all the P.p at a timeA B C D E F G H I J$echo $@A B C D E F G H I J

Note: 'Shift' command is used to shift the values of p.p.

$set A B C D E F G H I J$shift 1 ->to shift the p.p to one level back(left)$echo $1B$echo $#9$echo $@B C D E F G H I J$

Page 82: unix.pdf

Program to Display special paramter values:

$vi test

echo First p.p value:$1echo No. of p.p involved:$#echo Value of all p.p:$@echo Program Name:$0

:wq

$sh test This is unix

$?->It holds the status of recently executed command if command executed successfully its value zero

if command execution fails, its value other than zero

$grep -w oracle /etc/passwd>/dev/null$echo $?0 ->command executed successfully$grep -w oracl /etc/passwd>/dev/null$echo $?1 ->command execution fails

Process Status(ps):

$ps ->display all the processes runnin in linux server for given user$ps -ef -> Display all the processes running in linux server

$ps -ef|grep -w visix ->Display only visix user processes.

Killing process:

SYntax:

Page 83: unix.pdf

Kill <processId>

$kill -9 5012 -> -9 for sure killing

init runlevels: Run levels are used to control the server from root login

#init 0 -> To shut down server

#init 6 ->To Reboot server

$init 1 ->single user mode only root user can connect

$init 2 or init3 -> multi user mode but GUI not available

$histroy 10 ->display recently fired 10 command.

Functions: we can write set of statements under a name without opening file in vi editor.

Syntax:

function <function_name>(){ ................ ................. ................. }

Executing function:

Syntax:

<function_name>

$function test_fun(){

Page 84: unix.pdf

echo welcome to functionecho This is unix function }

Executing function:

$test_fun

.mainfunc.sh:- Functions created in this hidden file are perminant.

$pwd/home/oracle$vi .mainfunc.shfunction sum_fun(){a=$1b=$2c=`expr $a + $b`echo sum is:$c}

$. .mainfunc.sh

$sum_fun 4 8

Array:- it is collection of elements of continuous

memory locations. -> Using array we can store more than one value in single variable.

$a=(10 20 30 40)

$echo ${a[0]}10 ->first location value displayed.

$echo ${a[4]} ->fifth location value displayed.

$c=`expr ${a[0]} + ${a[4]}`

Page 85: unix.pdf

$echo $c

Note:-Set command display all the existing arrays. ->above array valid only for one session to make it perminant, declare above array in .bashrc.

Scheduling the Jobs:

1) at :- Used to schedule the jobs for single time execution.

$at now + 7 minutesat>rm -rf * -> rm -rf * executed after 7minutes from scheduledtime.at> ->type ctrl+d to come out from at

$

$at now + 2 monthsat>sh script22 -> Script22 executed after 2months from scheduled date and time.at> ctrl+d ->to come out

$

$at -t 201312150930at>sh script44 -> script44 executed on 15/dec/2012 at 9:30 AM.at> ctrl+d$

$atq -> Display all at scheduled jobs with jobids,execution time and scheduled username.

Page 86: unix.pdf

$at -c 32 -> Display the details of job with jobid-32.

$atrm 32 -> job with jobid-32 is removed from at schedule.

2) batch:- ->used to schedule the jobs for single time

execution. ->Job executed only when server is free.

$batchat>sh script33 -> script33 executed when server is free.at> ctrl+d -> to come out$

$atq -> Display scheduled job with jobid,scheduled time and username.

3) crontab:- It is used to schedule the jobs for regular execution.

Commands:

1) crontab -e -> Open editor for scheduling the jobs

2) crontab -l -> List the jobs which are scheduled using crontab

3) crontab -r -> Remove all the crontab scheduled jobs.

$crontab -e#minutes hours dayofmonth monthofyear wkdays sh <script>

Page 87: unix.pdf

# 00-59 00-23 01-31 01-12 0-6 * * * * * sh script22 ->script22executed forevery min. 30 10 * * * sh script44 ->script44 executed every day at 10:30AM 45 22 1,2 * * sh script55 ->script55 executed ever month 1,2 at 10:45PM

Searching for files:

1) which:- It is used to search for unix executable.

$which pwd

$which date

2) whereis:- used to search for unix executable and

manual help pages path of command.

$whereis pwd

$whereis date

3) find:- used to search for file in given directory.

$find file1 ->search for file1 in current working directory

$find abc/a1/a2/file1 -> search for file1 in a2 directory

Page 88: unix.pdf

$find|grep file1 -> search for file1 in c.w.d and all sub-dir in current working directory.

4) locate:- used to search for file in entire unix file system from root(/) directory on wards.

AWK

A->AhoW->WeinbergerK->Kernighan

-> It uSed to extract fields from file and also used to perform arithmetic operations between fields ->It will recognize the fileds if the field separator is tab or space. -> Print is used to print fields data from the file.Syntax:

awk [option] 'selection criteria {action}' file(s)

Arithmetic operators:+-*/%Comparison OPeratros:<<=>>=

Page 89: unix.pdf

!=== -> equalLogical operators:

&& -> AND|| -> OR

Builtin varibales :

$0 -> specifies entire file.

$1,$2,... specifies 1st,2nd,... fields

NR -> specifies cumulative no.of records required in output.

RS -> Input record separator.

OFS -> Out put field separator.

$vi inv1 pen 20 25.002 pencil 50 5.503 rubber 50 2.005 books 100 50.00

$awk '{print $0}' inv ->Display complete data from inv file.

$awk '{print $1" "$2}' inv ->Display 1st and 2nd fields of inv file.

$awk 'NR==2{print $0}' inv ->Display 2nd records of inv file

Create inv2 file with following data.

Page 90: unix.pdf

$vi inv21:pen:20:25.002:pencil:50:5.503:rubber:50:2.005:books:100:50.00

$awk -F':' '{print $1" "$2}' inv2 ->Display 1st and 2nd fields data from inv2 file ->-F option should be used to specify the filed separator if field separator is other than tab or space.

Scp(secure Copy):This command is used to copy files

from login to login in same or different unix servers.

Syntax:

scp sourceusername@Source_serverip:pathoffile targetuser@target_srip:destination path

$scp [email protected]:/home/yash/scpfile [email protected]:/home/oracle

Links: In linux links are classified into two types

i) Hard link ii) Soft link

Page 91: unix.pdf

->Every file or directroy contains one unique identification number called i-node number.

$ls -i ->Display all files and subdir., with i-node numbers.

i) Hard link:- It is pointer for i-node of file.

$pwd/home/yash$cat>file1sdfsdfsdfsdsdfsdfsdfsdfsdfsdfsdf

$ln file hf1 ->hf1 is hardlink for file1

$ls -i ->i-node numebrs of file1 and hf1 are same

Note: changes performed on file1 visible through hf1 and reverse also valid.

->if file1 removed, still we can access data through hf1

ii) soft link:- It is pointer for filename.

$ln -s file1 sf1 ->sf1 is soft link for file1

$ls -i ->i-node numbers of file1 and sf1 are different ->size of sf1 is smaller than file1

NOte:- Changes performed on file1 or hf1 or sf1 visible through file1,hf1,sf1.

Page 92: unix.pdf

->if file1 removed, sf1 becomes invalid.

Removing the Link:

Syntax: unlink <soft/hard linkname>;

$unlink sf1$unlink hf1

Conneting to oracle:

$logname oracle$sqlplus scott/tiger

SQL>cl scr; -> to clear the screen

SQL>select * from v$version; -> Display the version of oracle.

SQL>select * from dept; -> Display data from dept table.

SQL>! -> to go back to linux

$

$exit -> to go back to oracle

SQL>

SQL>exit -> to disconnect from the oracle.

?WAS to display data from dept table in scott login;

$vi orascriptsqlplus -s scott/tiger<<EOF

Page 93: unix.pdf

select * from dept;EOF

Zipping the files:-

1) zip

2) gzip

3) bzip2

4) tar

1) zip:- used to zip two or more files.

$zip myfile.zip file1 file2 -> file1,file2 are added to myfile.zip

$rm f*

$unzip -l myfile.zip -> Display all the files in zipped file.

$unzip myfile.zip -> extracting files from zipped file.

$unzip myfile.zip file1 ->file1 only extracted

2) gzip:- used to zip single file.

$gzip file1 -> file1 renamed to file1.gz

$zcat file1.gz -> display data from the zipped file

$gunzip file1.gz -> unzip the zipped file.

Page 94: unix.pdf

3) bzip2:- It is also used to zip a single file and it is newly introduced in linux.

$bzip2 file1 -> file1 renamed to file1.bz2

$bzcat file1.bz2 -> display data from the zipped file

$bunzip2 file1.bz2 -> Unzip the zipped file.

4) tar:-it is used to archive the files or directories. It is generally used for taking backups.

$pwd/home/oracle

$tar -cvf bkp.tar /home/oracle c-> create v-> verbose i.e Display files while adding the tar file f-> file

$tar -tf bkp.tar -> Display all the files in the tar file$tar -tvf bkp.tar

$tar -xvf bkp.tar -> Extracting files from tar file

$tar -czvf newbkp.tar /home/oracle ->applying tar command and zipping the file.

Page 95: unix.pdf

Scheduling the Jobs:

1) at :- Used to schedule the jobs for single time execution.

$at now + 7 minutes

at>rm -rf * -> rm -rf * executed after 7minutes from scheduled time.at> ->type ctrl+d to come out from at

$

$at now + 2 monthsat>sh script22 -> Script22 executed after 2months from scheduled time.at> ctrl+d ->to come out

$

$at -t 201212150930at>sh script44 -> script44,script55 are executed on 15/Dec/2012 at 9:30 AM.at> sh script55$

$atq -> Display all at scheduled jobs with jobids,execution time and scheduled username.

$at -c 32 -> Display the details of job with jobid -32.

$atrm 32 -> job with jobid-32 is removed from at schedule.

2) batch:-

Page 96: unix.pdf

->used to schedule the jobs for single time

execution. ->Job executed only when server is free.

$batchat>sh script33 -> script33 executed when server is free.at> ctrl+d -> to come out$

$atq -> Display scheduled job with jobid,scheduled time and username.

3) crontab:- It is used to schedule the jobs for regular execution.

Commands:

1) crontab -e -> Open editor for scheduling the jobs

2) crontab -l -> List the jobs which are scheduled using crontab

3) crontab -r -> Remove all the crontab scheduled jobs.

$pwd/home/visix$vi crontab -e

#minutes Hours dayofmonth monthofyear wkday sh <scriptname> 00-59 00-23 01-31 01-12 0-6 * * * * * sh script2 ->script2 executed for every minute.

Page 97: unix.pdf

30 10 * * * sh script44

->script44 executed every day at 10:30 AM 45 22 1,2 * * sh script66 ->script66 executed every month 1st,2nd at 10:45 PM:wq

$crontab -l ->display all the schedules jobs.

$crontab -r ->remove all the crontab scheduled jobs

Communicating with users:

1) wall:- used to send a common message to all the users connected to server.

$wall Hi all users -> all users connected to server will receive the message.

2) write:- Used to communicate with particular user connected to server.

$lognameoracle

$write visix -> only visix user will receive the messages.........................ctrl+d -> to come out from write.

Page 98: unix.pdf

$mesg n -> user will not receive messages from others

$mesg y -> now user will receive messages from others.

Searching for files:

1) which:- It is used to search for unix executable.

$which pwd

$which date

2) whereis:- used to search for unix executable and

manual help pages path of command.

$whereis pwd

$whereis date

3) find:- used to search for file in given directory.

$find file1 ->search for file1 in current working directory

$find abc/a1/a2/file1 -> search for file1 in a2 directory

$find|grep file1 -> search for file1 in c.w.d and all sub-dir in current working directory.

4) locate:- used to search for file in entire unix file system from root(/) directory on wards.

Page 99: unix.pdf

$locate newfile ->search for newfile in entire unix file system from root directroy onwards.

Creating and executing C program:

i) C program t display message

$vi test.c#include<stdio.h>main(){printf("Hello C\n");}

ii) Shell script to execute above C program:

$vi cscript

cc -c test.c ->Compiliation of c-programcc -o myc test.o ->An executable file myc createf for test.o./myc ->Executing Executiable file

:wq

iii) executing Shell script

$sh cscript

Creating and Executing C++ program:

i) Creating C++ program

$vi newtest.cpp

#include<iostream.h>main(){cout<<"Hello CPP\n";

Page 100: unix.pdf

}

:wq

ii) Shell Script to execute above c++ program

$vi cppscript

g++ -c newtest.cpp ->compiliation of c++ program and an object file newtest.o is created

clearg++ -o mycpp newtest.o./mycpp

:wq

iii) sh cppscript ->executing the Shell script

Creating and executing Java Program:

$vi jtest.java

class jtest{public static void main(String [args]) {System.out.println("Hello Java"); }}

:wq

Executing above java program:

$java jtest.java$java jtest

Page 101: unix.pdf

:wq

Executing Shell script

$sh orascript ->Data in dept table displayed.

Page 102: unix.pdf
Page 103: unix.pdf
Page 104: unix.pdf
Page 105: unix.pdf
Page 106: unix.pdf
Page 107: unix.pdf
Page 108: unix.pdf
Page 109: unix.pdf
Page 110: unix.pdf
Page 111: unix.pdf
Page 112: unix.pdf
Page 113: unix.pdf
Page 114: unix.pdf
Page 115: unix.pdf