Sei sulla pagina 1di 160





  !

| 

            


Index

| 

            


i IX Operating System

| 

            "


Objectives

^ Introduction to OS concepts
^ Introduction to Unix Operating System
^ Unix System Architecture
^ Introduction to Unix File System
^ Starting to work with UNIX

| 

            #


Operating System

^ Is a System software
^ Can be defined as
^ An Organized collection of software consisting of
procedures for operating a computer
^ Provides an environment for execution of programs
^ Acts as an interface between the user and the hardware of the
computer system.

| 

            $


Objectives

^ Operating system interacts with the user in two ways


Operating system calls
^

Provides an interface to a running program and the


operating system. System calls in UNIX is written in C.
Operating system commands
^

Enables the user to interact directly with the


operating system.

| 

            %


istory of i IX

^ ren Thompson of AT&T ,BELL laboratories originally


designed UNIX in late 1960s which evolved from
timesharing operating system called multics.
^ Originally written in assembly language but with the
development of µc¶ programming language in 1973,it was
then written in µc¶.
^ Two versions of UNIX emerged are AT&T Unix and BSD
Unix

| 

            &


istory of i IX

^ 1989 AT&T and Sun Micro system joined together and


developed system V release 4 (SVR4)

^ Two of the main standards mainly in use are


POSIX(Portable Operating System Interface) and X/open
standard

^ 1988 MIT formed Xconsortium which developed vendor


Neutral Xwindow System

| 

            '


ºeatures of i IX

^ Multi-user /multitasking/timesharing concept


^ Portability
^ Modularity
^ File structure
^ Security
^ Strong networking support
^ Advance graphics

| 

            (


i IX Operating System

^ Multi-user, Multiprocessing Operating System


^ Consists of several dumb terminals attached to it.
^ Written in high-level language C
^ Uses hierarchical file system - allows easy maintenance and
efficient implementation

| 

            


i IX System Architecture

^ Unix System follows a layered Approach


^ It has four layers
^ The innermost layer is the hardware layer
^ In the second layer, the kernel is placed.
^ The utilities and the other application programs form the third layer
^ Fourth layer is the one with which the user actually interacts.

| 

            


Layered Architecture

  

 



à
 à  

 


   Other
  application

programs

| 

            


rernel

^ rernel is that part of the OS which directly makes interface with


the hardware system.
^ Factions:
^ Provides mechanism for creating and deleting processes
^ Provides processor scheduling, memory and IO management
^ Does interprocess communication.

| 

            "


Ôhe Shell

^ A Utility program that comes with the unix system.


^ Features of Shell are:
^Interactive Processing
^Background Processing
^I/O Redirection
^Pipes
^Shell Scripts
^Shell Variables
^Programming Constructs

| 

            #


ïrocess management

^ A process is a program in execution


^ Several processes can be executed simultaneously in a
UNIX system.
^ A process is generally created using the ³fork´ system call.
^ The process that invoked the ³fork´ system call is the parent
process and the newly created processed are called as child
processes

| 

            $


Yïi Scheduling

^ Unix uses ³Round-Robin´ scheduling to support its multi-user and


time-sharing feature.
^ Round-Robin fashion of scheduling is considered to be
oldest,simplest and widely used algorithm.
^ Here, every process is given a time slice(10-100 millisec.)

| 

            %


Aemory management

^ Swapping
^ Demand Paging

| 

            &


ºile management

^ Unix uses a hierarchical file system with ³/´ as its root.


^ Every non-leaf node of the tree is called as a directory file.
^ Every leaf node can either be a file or an empty directory

| 

            '


ºile system

dev bin tmp home etc var lib usr


spool
sh inittab bin src
console ls password
user1
lp0
user2

| 

            (


ºile system

^ File system is the structure in which the files are stored in the
disk

^ File in UNIX is sequence of bytes organized in the form of


blocks.

^ The size of each block is 512 bytes (depends on architecture)

^ Block size can be decided while creating the file system


structure

| 

            


ºile system structure
Ôype of the file
Link counter
Ooot Olock iid, gid, size
Date and time of
Super Olock Yreation
Date and time of access
Inode Olock Date and time of
modification
Data Olock Address
: of datablock
:
Address of datablock
:
:
Address of the datablock
Address of the datablock
Address of the datablock

| 

            


| 

            


Yommon i IX flavours

VOSD: Oerkeley, OSD

VSolaris: Sun Aicrosystems, Sys 5/OSD

Viltrix: Digital Equipment Yorporation, OSD

VOSº 1: Digital Equipment Yorporation, OSD/sys 5

VïiX: ewlett-ïackard, Sys 5

VAIX: IOA, Sys 5 / OSD

VIRIX: Silicon Graphics, Sys 5

VG i/Linux: G i, OSD/ïosix

| 

            "


i IX classification

^ The Owner
^ Group member
^ other users

| 

            #


orking with i IX

^ Log in
^ Log out

| 

            $


i IX YOAAA DS

| 

            %


Simple commands

^ pwd
^ Identifies the current working directory.

^ date
^ Displays the current date and time

^ who
^ Displays the names of all the users who have currently
logged in
^ who am i
^ Displays the name of the current user.

| 

            &


Listing the directory contents

ls
Syntax :ls [options] [file«.]
options:-l list in long format
-a list all file including those
beginning with a dot
-i list inode no of file in first column
-s reports disk blocks occupied by file
-R recursively list all sub directories
-F mark type of each file
-C display files in columns

| 

            '


Aeta characters

u 0 or more characters
? 1 character
[-] matches any one character between the brackets
[^ ] not matches any one character in the brackets

| 

            (


Listing the directory contents
groupid Size in bytes
Link counter
ù ls ±l

total 6
-rwxr-xr-x 1 user1 training 12373 Dec 15 14:45 a.out
drwxr-xr-x 2 user1 training 4096 Dec 22 14:00 awkpro File name
-rw-r--r-- 1 user1 training 12831 Dec 12 13:59 c
-rw------- 1 user1 training 61440 Dec 15 11:16 core
-rw-r--r-- 1 user1 training 255 Dec 20 14:29 cs

userid

Date &Time of
File access Modificaion
permission
Type
of file

| 

            "


Getting help about commands
The Unix manual, usually called   , is available on-line to
explain the usage of the Unix system and commands. To use a
man page, type the command "" at the system prompt
followed by the command for which you need information.
Syntax:
 [options] command_name

 )
*+ keyword list command synopsis line for all keyword
matches
*, path path to man pages
* show all matching man pages (SVR4)

 command_name * help for the internal commands


  *-command_name- gives command synatx

| 

            "


ºiles & Directories

| 

            "


Objectives

^ File Permissions

^ Directory Related Commands

^ File Related Commands

| 

            ""


ºile access permissions

^ Refers to the permissions associated with a file with respect to


the following

^ Permission Levels
^User (owner) (Œ)
^Group (wheel, staff, daemon, etc.) ()
^World (guest, anonymous and all other users) ()

^ Permission Settings
^Read ()
^Write (Ñ)
^Execute ()

| 

            "#


ºile access permissions

^ No read permission does not allow the user to:


^List the contents of directory
^Remove the directory
^ No Write permission does not allow the user to :
^copy files to the directory
^remove files from the directory
^rename files in the directory
^make a subdirectory
^remove a subdirectory from the directory
^move files to and from the directory

| 

            "$


ºile access permissions

^ No execute permission does not allow the user to:

^ display the contents of a directory file from within the directory

^ change to the directory

^ display a file in the directory

^ copy a file to or from the directory

| 

            "%


Yhanging permissions - chmod

chmod u+x file_name


Syntax:
chmod <category> <operation> <permission> <filename(s)>
Or
chmod <octal number> filename

Octal Number
r -4
w -2
x -1
ù chmod 744 xyz
this will set rwx for user, r± for group, r²for others

| 

            "&


| 

            "'


Directory creation
Command Syntax
mkdir [OPTION] DIRECTORY
ùmkdir <path>/<directory>
ùmkdir ±m <directory>
ùmkdir ±p <directory1>/<directory2>/<directory3>

Example:
^mkdir project1
This creates a directory project1 under current directory

Note:
Write and execute permissions are needed for the user to create a
directory

| 

            "(


Directory removal

rmdir command removes directory


Syntax
^rmdir <directory name>
Example
Removes project1 directory in the current directory
^ rmdir project1
Remove multiple directories
rmdir pos1 pos2
Remove the directory recursively
rmdir ±p dir1/dir2/dir2
Rule: m m 
 m m      

mm m m 

| 

            #


ºile related commands

FILE OPERATIONS COMMANDS

Copying a file cp

Moving a file mv

Removing a file rm

Displaying a file cat

| 

            #


Yommand - cp

Used to copy files across directories


Syntax
cp <source file> <new file name>

Example
cp file1 file2

Note:
cp -r /dev/tty myfile

| 

            #


Yommand - cp

^ -p preserve following file attributes


^ owner id
^ Group id
^ permissions
^ Last modification time

^ -r
Recursive copy; copy subdirectories under the directory if
any

| 

            #"


Yommand - mv
Used to move a file or rename a file

Preserves the following details


owner id
^

group id
^

permissions
^

Last modification time


^

-f suppresses all prompting

-i prompts before overwriting destination file

| 

            ##


Yommand - rm
Used to remove a file
Syntax : rm file(s)
^

-f suppresses all prompting

-i prompts before overwriting destination file

-r will recursively remove the file from a directory (can be used to


delete a directory along with the content )

Caution: Use ³i´ option along with ³r´ to get notified on deletion

| 

            #$


Yommand ± chown & chgrp
ù ls ±l total 156
-rwxr-xr-x 1user1 training 12373 Dec 15 14:45 a.out
-rwxr-xr-x 3 user1 faculty 4096 Dec 24 11:56 awkpro

ùchown user2 a.out

ùls ±l
-rwxr-xr-x 1user2 training 12373 Dec 15 14:45 a.out
-rwxr-xr-x 3 user1 faculty 4096 Dec 24 11:56 awkpro

ù chgrp training awkpro

ùls ±l
-rwxr-xr-x 1user2 training 12373 Dec 15 14:45 a.out
-rwxr-xr-x 3 user1 training 4096 Dec 24 11:56 awkpro

| 

            #%


Yommand - umask

umask value is used to set the default permission of a file and directory
while creating

umask command is used to see the default mask for the file
permission

Default umask value will be set in the system environment file like
/etc/profile

umask 022 will set a mask of 022 for the current session
The file permission after setting this umask value will be 644
^

And the directory permission will be 755


^

| 

            #&


Yommand - ln

Linking files

^ Hard Link (in the same filesystem)


ù ln /usr/bin/clear /usr/bin/cls
^

^ Hard link uses the same inode number

^ Soft Link (in different filesystems also used to link


directories)
^ù ln ±s /usr/bin/clear /home/user1/cls

| 

            #'


Special permission bits
^ Set user ID (SUID)
^ Typically set to an executable program
^ The effective user ID of the process that runs the program
will be the owner ID of the program

^ Set group id (SGID)


^ Typically set to an executable program
^ The effective group ID of the process that runs the program
will be the group ID of the program

^ Sticky bit
^ Typically set to a directory that is sharable
^ This allows individual users to create/delete their files
^ Only the owner or root has the privileges to remove any file
in the directory
| 

            #(


vi editor
Vi is a visual editor used to enter and edit text files.
^ A screen-oriented text editor
^ Included with most UNIX system distributions
^ Command driven
Categories of commands include
^ General administration
^ Cursor movement
^ Insert text
^ Delete text
^ Paste text
^ Modify text
The vi editor is invoked by the following command
^ vi <filename>
| 

            $


Editing commands
^ Text insertion / replacement

^ i - inserts text to the left of the cursor


^ a - inserts text to the right of the cursor
^ I - inserts text at the beginning of the line
^ A - appends text at end of the line
^ o - opens line below
^ O - opens line above
^ R - replaces text from cursor to right
^ s - replaces a single character with any
number of characters
^ S - replaces entire line

| 

            $


Editing commands
^ Deletion
^ -x - to delete character at cursor position
^ -3x - to delete 3 characters at cursor position
^ dw - to delete word
^ -2dw - to delete 2 word
^ dd - to delete a line
^ 2dd - to delete 2 lines

| 

            $


Editing commands
^ Yanking
^ Y - copy line into buffer
^ 3Y - copy 3 lines into buffer
^ p - copy buffer below cursor
^ P - copy buffer above cursor

^ Save and quit


^ :w - to save
^ :w! - to name a file (:w! filename -> )
^ :x - save and quit
^ :q - cancel changes
^ :q! - cancel and quit

| 

            $"


Search & replace commands
:s/old/new/g to substitute 'new' for 'old'.

:s/thee/the change the first occurrence of


thee with the.

:s/thee/the/g substitute globally thee with the

To change every occurrence of a character string between two lines,

:#,#s/old/new/g where #,# are replaced with the numbers of


the two lines.

:%s/old/new/g to change every occurrence in the whole file.

| 

            $#


Yustomizing vi

^ :set number ù cat .exrc


set number
^ :set nonumber
set tabstop=6
^ :set ignorecase
^ :set nomagic
^ :set showwatch
^ :set tabstop=6

| 

            $$


avigation

Backspace Space

h j k l

the quick brown fox the quick brown fox

w w w ù
the quick brown fox the quick brown fox

2 w ^
the quick brown fox

b b b

| 

            $%


inix itilities

| 

            $&


Objectives

General purpose utilities


cat, echo, touch, more, file, wc, cmp, comm, find, banner, cal
^

etc..

Redirection operators

Filters

| 

            $'


cat

cat is concatenate files and print on the standard output


cat command takes the input from the keyboard and send the
output to the monitor
We can redirect the input and output using the redirection operators
^ù cat>file1
^Type the content here
^press <ctrl d>
^ù cat file1
^Displays the content of the file
^ùcat>>file1
^Will append to the content of the file

| 

            $(


touch

Syntax: touch [options] file


Options:
^a to change the access time
^m to change the modification time
^c no create if not exists
touch is used to change the time stamp of the file

Touch <file> will change the time of change of the file is the file
exists

If the file is not existing it will create a file of zero size

| 

            %


echo

echo command is used to print an output to the screen

echo ³This is an example´


This is an example

x=10

echo ùx
10

| 

            %


General purpose utilities

more
^ Allows the user to view one page full of information at a time.
file
^ Used to display the type of the file
tty
^ Prints the terminals name

| 

            %


General purpose utilities

wc
^ A filter used to count the number of lines,words and characters
in a disk file or in the standard input.
^ -l - displays the number of lines
^ -w - displays the number of words
^ -c - displays the number of characters

| 

            %"


General purpose utilities

cmp
^ Returns the offset and the line number and the line number of
the first position where the two files differs.

comm
^ col1 - unique lines of first file
^ col2 - unique lines of second file
^ col3 - common lines

| 

            %#


General purpose utilities

diff
^ Indicate the differences between the files
^ a Lines added
^ d Lines deleted
^ c Lines changed

| 

            %$


General purpose utilities

find
^ Used to locate a file or a directory in the given path
Usage
find <path> [options]
^

Options
name - accepts the format to searched
^

print displays the path on the screen


^

| 

            %%


| 

            %&


General purpose utilities

pr
^ Used to display a file in a format to be printed.
^ Breaks up a file into pages with a header, text and footer area

Options
-l
^ to alter the length of the file
-h
^ to set the header
-t
^ to suppress the header and the footer

| 

            %'


Standard files

Standard Input file


reyboard , file descriptor is 0
^

Standard Output file


Monitor , file descriptor is 1
^

Standard Error file


Monitor, file descriptor is 2
^

| 

            %(


I/O redirection

< file redirect standard input from file


> file redirect standard output to file
2> file redirect standard error to file
2>&1 merge standard error with standard output

ù cat > abc

ù ls ±l > outfile

ù cat xyz abc > outfile 2> errfile

ù cat xyz abc > outfile 2>&1

| 

            &


ºilters

Filters are programs that takes its input from the std i/p file,
processes it and sends it to the std o/p file.

Commonly used filter commands


sort
^

grep
^

cut
^

head
^

tail
^

paste
^

| 

            &


sort

Sorts the contents of the given file based on the first char of each
line.
-n --numeric sort
-r --Reverse sort
-t -Specify delimiter for fields

+num -specify sorting field numbers


+num -num - to specify the range

can specify the characters in the field

| 

            &


grep

Grep -Global Regular Expression Printer


Is used for searching regular expressions
Syntax
^grep <options> <pattern> <filename(s)>

| 

            &"


grep options

-c displays count of the number of occurrences

-n displays line numbers along with the lines

-v displays all lines except lines matching pattern

-i Ignores case for matching

| 

            &#


patterns
u - matches 0 or more characters

[^pqr] - Matches a single character which is not p ,q or r

^pqr -Matches pqr at the beginning of the line

pqrù -Matches pqr at the end of the file

³.´ - Matches any one character

\ - ignores the special meaning.


^Grep ³New\[abc\]´ filename

| 

            &$


ºilter command - head

Displays the top n lines of the file

Can specify top n lines to be displayed

ù head -3 file1

| 

            &%


ºilter command - tail

Displays the end of the file


Can specify last  lines to be displayed

ù tail -3 file1

Can also specify the line number from which the data has to be displayed

ù tail +5 file1

| 

            &&


ºilter command - tr

tr - Transtlate filter used to translate a given set of characters

usage :
tr [a-z] [A-Z] filename
^

option -s can be used to squeeze the repeated characters.

| 

            &'


Yommand piping

^ Allows the output (only the standard output) of a command to be


sent as input to another command.

^ Multiple pipes may appear in one command line.

Example:

ù cat u | wc

ù cat fil1 | head | wc -l

| 

            &(


ºilter command ± tee

^ tee command allows the normal output to the standard


output, as well as to a file
^ iseful to capture intermediate output of a long command
pipeline for further processing or debugging purpose.

Example
who | tee userlist
^

cat - | tee file1 | wc -l


^

| 

            '


ºilter command ± cut

Used to extract specified columns from the o/p of certain


commands
-c used to extract characters
-d Delimiter for fields
-f Field no.
Examples
cut -c2-5 file1
cut -d ³|´ -f2,3 file1

| 

            '


ºilter command ± paste

Paste is used to fix two cut portions of the file vertically

-s -->Pastes the contents of file2 below file1

-d -->Specify delimiter

ù paste -d´|´ file1 file2

| 

            '


Yonnecting to Remote Systems
à
 
Allows a connection to host from any other machine connected to the Internet. node
itself will prompt for a logon name, then the password.
Logging on remotely allows users to use the i IX/Linux commands, but not the
Graphics iser Interface of the remote machine.

Oypassing ïassword - (non-secure)
rlogin: rlogin node
Allows a connection to node without the use of a password. ºor this to be true, two
things must be properly set.
1.You must have an account (of the same name) on the remote system.
2.ºile .rhosts on the remote system must contain the name of the local system,
followed by your account name.

| 

            '"


º 

á à
 
put/send: Ôransfer to Other hosts

put [local_file [remote_file]]

get/recv: Ôransfer ºrom Other hosts

get [remote_file [local_file]]

mput: Aultiple Ôransfer to Other hosts

It will prompt for every file to be transferred, unless the -i flag was used
on the ftp command line, or the prompt command is issued.
mput is very useful when moving a number of files.

| 

            '#


Yompression utilities

 
isage is very similar to compress and pack utilities in unix:
gzip [-vc] filename
where -v displays the compression ratio.
-c sends the compressed output to standard output and leaves the original file
intact.

6
gunzip can uncompress files originally compressed with compress.

| 

            '$


tar ± tape archive

tar is a utility that packs a list of files (and/or directories) into a specific tarfile,
whose name typically ends in .tar.
tar is invoked by

tar -c|t|x [vof destination] source...

where destination is the name of the tape device or tar file, and source... may be files
and/or directories combined to produce the tar file. One of c, t, or x must be
used.

| 

            '%
tar ± tape archive
-c (create): creates a new tarfile.
-t (table): lists the files on the tarfile.
-x (extract): extracts the files from the tarfile.
-v (verbose): the size and name of each file put onto or extracted from the tarfile is
displayed.
-o (ownership): on the extraction of files, do OÔ extract the original ownership of
the files and directories. Ôhis avoids the message permission denied when reading
tar_files.
-f (destination): uses the next argument as the name of the tarfile.
It is normally in the form filename.tar (but could also be a device name, such as
/dev/8mm).

| 

            '&
ïrocesses

| 

            ''


ïrocesses

Process related commands

^ ps
^ kill
^ wait
^ sleep

| 

            '(


ïrocesses

^ Process - a program in execution

^ When program is executed , a new process is created

^ The process is alive till the execution of the program is complete

^ Each process is identified by a number called pid.

| 

            (


Login shell

As soon as the user logs in, a process is created which executes the
login shell.

Login shell is set for each login in /etc/passwd directory.

| 

            (


ps
The ps command is used to display the characteristics of a process

It fetches the pid, tty, time and the command which has started the
process.
^ -f lists the pid of the parent process also.
^ -u lists the processes of a given user
^ -a lists the processes of all the users
^ -e lists all the processes including the system processes

| 

            (


Oackground process

Enables the user to do more than one task at a time.

If the command terminates with a & UNIX executes the command at


the background

| 

            ("


| 

            (#


Yontrolling background processes

jobs
^ List the background process
fg %
^ Runs a process in the foreground
bg %
^ Runs a process in the background
nice

| 

            ($


kill command

^ kill : rills or terminates a process

^ rill command send a signal to the process


^ The default signal is 15 ( SIGTERM)

^ rill -9 (SIGrILL)
^ Terminates the process abruptly

| 

            (%


/etc/passwd file

^ Sample entries

root:x:0:0:root:/root:/bin/bash
xfs:x:43:43:X Font Server:/etc/X11/fs:/bin/false
suresh:x:500:500:SURESH:/home/suresh:/bin/bash
perumal:x:501:501::/home/perumal:/bin/bash
user:x:502:502::/home/user:/bin/bash
user1:x:503:503::/home/user1:/bin/bash

| 

            (&


Shell ïrogramming

| 

            ('


| 

            ((


Introduction to
Shell ïrogramming

| 

            


ºlavors of shell

^ Bourne shell sh developed by Stephen Bourne

^ C shell csh ,, ,, Bill Joy

^ rorn shell ksh ,, ,, David korn

^ Bourne again bash Shell distributed with linux shell

| 

            


Shell features

^ Displays the shell prompt and reads the command typed by


the user.

^ Interprets the command and classifies it as internal (built-in)


or external command.

^ If it is a NOT a built-in command, searches for the


command in the PATH specified directories and executes
that command if it is found.

| 

            


Shell features

| 

            "


Shell features

ï  

ù  

   



 

  
 
iser Aode

rernel Aode

| 

            #


Additional shell features

^ Each shell, apart from the basic features, provides additional


features such as:

^ Maintaining command history (C, korn and bash)

^ Renaming (aliasing) a command (C, korn, bash)

^ Command editing (C, korn and bash)

^ Programming language (all shells)

| 

            $


istory

Ôhe history concept provides the user with the capability of calling and editing
previously used commands, modifying others, listing the last commands used,
and so on. ere are some of the commands using the Y shell history concept:

ÚÚ recall the last command and execute it.

Ú  where num is a number, recall and execute


command number num.

history recalls and list the last commands used.

| 

            %


alias

Ôhe alias mechanism provides the user with the ability to rename a command, or
change the default options of a command.

Ôhe list of aliases is usually defined in either the .cshrc file in the user's home
directory and/or in /etc/cshrc X 
in linux)

alias [command def]


where command is the name of the new command, and def is how it is to be
executed. alias typed on a line by itself will list all current aliases.

Ôo create a new command called erase to work as the rm command:



  
 
   
ºrom that point on, typing erase will be the same as typing rm.
Ôhe unalias command cancels alias.
| 

            &


Yommand processing by shell

^ If the command is a built-in shell command, the shell executes


the command.

^ If the command is not a built-in shell command, the shell looks


up the list of directories specified by the PATH environment
variable, and finds a program (having the same name as the
command entered or looking up at an alias table) that will
perform that command.

^ If the shell cannot find the command in the directories specified


by PATH, it displays an error message. Otherwise it executes
the command.

| 

            '


ºile name substitution

^ When the user enters a command string, the shell parses the
string into following components:

^ Command(the first part of the string)


^ Command arguments (the subsequent parts of the string)

^ For example, if you enter a command-string such as ³ls ±l u.c´,


this string contains the ³ls´ command and two arguments ³-l´ and
³u.c´.

| 

            (


ºile name substitution

^ In arguments of a command, the shell recognizes certain


characters ± such as u, ?, [, ], and . - as special characters and
expands these characters into a filename list before executing
the command.

^ To see how this works, enter following commands:

^ echo ³this is a message´


^ echo this is a message
^ echo u

| 

            


I/O redirection

^ The shell provides facilities to re-direct input, output and error


for a command through special characters:

^ Use > character to redirect output of a command to a file.


^ Use < character to redirect input to a command from a file.
^ Use >> characters to append output of a command to a file.
^ The > and 2>&1 characters redirect output and error of a
command to a file.

| 

            


I/O redirection

cat u.c > outfile


cat u.c >> outfile
cat nosuchfile > outfile
cat nosuchfile 2> outfile
cat u nosuchfile > outfile
cat u nosuchfile > outfile 2>&1
mail ùuser ±s ³testing IO redirection´ < outfile
cat u nosuchfile >> outfile 2>&1

| 

            


Input redirection special case

^ The shell supports a special case of input redirection that allows


you to ./  Œ   /  Ñ   
 .

^ For example, the  command expects it¶s input from the


standard input (keyboard) or a file. Therefore, if you use the 
command as follows in a shell script, it will expect the input to
come from the keyboard:
 0 Œ

| 

            "


Input redirection special case

^ In the previous example, if you wanted to provide input to the cat


command from within the shell script itself, you can use ll
   Ñ  1 . Consider following shell script:
^ ù vi testcat
cat > outfile << > 2>)3>24 4>
This data comes from a shell script
This data comes from a shell script
> 2>)3>24 4>
ù cat outfile

| 

            #


Shell programming

^ The shell allows you to assign values to variables. This is the


most basic feature required of a programming language.

^ The shell also provides other programming constructs including:

^ Condition checking
^ Loops
^ Input and output statements

| 

            $


Shell variables
^ Variable is a name associated with a data value and it offers a symbolic
way to represent and manipulate data.variables in the shell are classified
as follows

^ user defined variables


^ environment variables
^ predefined variables

^ value assigned to the variable can then be referred to by preceding the


variable name with a ù sign.

| 

            %
Executing shell script

There are two ways of executing a shell script:

By passing the shell script name as an argument to the shell.


For example:

sh script1.sh

If the shell script is assigned execute permission, it can be


executed using it¶s name. For example:

./script1.sh

| 

            &


Sample shell script

#! /bin/bash
#
# The above line has a special meaning. It must be the
# first line of the script. It says that the commands in
# this shell script should be executed by the bash
# shell (/bin/bash).
# ---------------------------------------------------------------
echo ³Hello ùUSER«.´
echo ³I hope you like working with shell scripts..´
# ---------------------------------------------------------------

| 

            '


Shell variables

^ The shell provides facility to define  and . 


variables.

^ A  variable can be only used in the shell where it is


defined. An .  variable can be used in the shell
where it is defined, plus any child shells invoked from that shell.

^ Therefore, if you define an environment variable, it can be used


within a shell script.

| 

            (


ising normal variable

^ To define a  variable, use following syntax:

.1 > 5.Œ

^ Examples:

ù 5
ù   >56   Ñ   / 1 ù 
ù   >57   Ñ   / 1 ù 
ù Œ 58Ñ8
ù ŒŒ 58Ñ 9 Ñ -8

| 

            


ising normal variable

^ Having defined above variables, you can use the echo


command to display the value of each variable:

^ ù echo ùx
^ ù echo ùtextline_1
^ ù echo ùtextline_2
^ ù echo ùallusers
^ ù echo ùcountusers

| 

            


ising environment variable

^ To define an .  variable, use following syntax:

.1 > 5.Œ


 .1 >

^ Examples:

ù 5:  
ù Œ 58Ñ8 :  Œ 

| 

            


Ouilt-in environment variables

^ bash shell provides a number of built-in environment


variables. These include:
^ PATH=/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:/usr/X
11R6/bin:/home/girish/
^ BASH_ENV=/home/girish/.bashrc
^ HOME=/home/girish
^ PWD
^ SHELL=/bin/bash
^ TERM=ansi
^ MAIL=/var/spool/mail/girish
^ USER=girish
^ LOGNAME=girish
^ PS1=`pwdù`
| 

            "


Shell meta characters

^ The Bash Shell recognizes a number of meta-characters. Each


meta character can represent zero or more ordinary characters.

^ These meta characters are used in:

^ Filename expansion
^ Variable assignment
^ Forming regular expressions etc.

| 

            #


Shell meta characters

^ These meta-characters are:

^ Asterisk - u
^ Question Mark - ?
^ Square brackets ± [ and ]
^ Single quote ± µ
^ Double quote ± ³
^ Back quote - `
^ Back slash - \

| 

            $


Shell meta characters

^ Examples:

ù x=u ; echo ùx
ù x=?????? ; echo ùx
ù x=[a-p]????? ; echo ùx
ù x=µùUSER sold the book for ù10¶ ; echo ùx
ù x=³ùUSER sold the book for ù10´ ; echo ùx
ù x=³ùUSER sold the book for \ù10´ ; echo ùx
ù x=`who` ; echo ³Current users = ³ ùx

| 

            %


ïassing parameters to scripts

^ You can pass parameter to a shell script by entering the


parameters after the name of the shell script.

^ Within the shell script, you can refer to the parameters through
variables ù1 through ù9.

^ If you need to use more than 9 parameters, you can use the
shift command within the shell script to refer to additional
parameters.

| 

            &


ïassing parameters to scripts

^ Consider following shell script:

----------------------script2.sh--------------------------
echo ³Total parameters entered: ù#´
echo ³First parameter is : ù1´
echo ³The parameters are: ùu´
------------------------------------------------------------

^ Execute the above script using the 7     


   command.

| 

            '


ïassing parameters to scripts

^ The shell parameters are passed as strings.

^ If you want to pass a string containing multiple words as a single


parameter, you must enclose the string within quotes. For
example,

ù script2.sh ³this string is a single parameter´

| 

            (


Doing arithmetic operations

^ You can use normal operators with the  command. For
example,
^ x=10, y=5
Œ1 > 5 8  ù ; ù8
Œ1 > 5 8  ù * ù8
Œ1 >" 5 8  ù < ù8
Œ1 ># 5 8  ù => ù8
Œ1 >$ 5 8  ù ? ù8

| 

            "


ising the test command

The general syntax of   command is:

  l  0

^ The   can be formed using a combination of shell


variables and the operators supported by the test command.
These operators provide facility to compare numbers, string and
logical values, file types and file access modes.

| 

            "


ising the test command

^ To compare two integers using   following operators are


available:

* @ (equal to)
* (not equal to)
* (less than)
* (less than or equal to)
* (greater than)
* (greater than or equal to)

| 

            "


ising the test command

^ Please note that you can only compare two integers using the
  command.

^ The syntax for this comparison is:

         


OR
A         B

| 

            ""


ising the test command

^ To compare two strings using the   command, following


operators are available:

^  5  (equal to, please note it is a single =)


^  C5  (not equal to)
^  (string is not NULL)
^ *  (string is not NULL and exists)
^ *D  (string is NULL and exists)

| 

            "#


ising the test command

^ The syntax for this string comparison is:

     


OR
A     B
OR
    
OR
A    B

| 

            "$


ising the test command

^ To check a file type/access permissions using the  


command, following operators are available:

^ *  (file is not empty)


^ *  (file is not a directory)
^ */  (file is a directory)
^ *  (file is readable)
^ *Ñ  (file is write-able)
^ *  (file is executable)

| 

            "%


ising the test command

^ To check a file type/access permissions using the  


command, following operators are available:

^ *1  (file is a block device)


^ *  (file is a character device)
^ *  (file is a named pipe)
^ *  (file has sticky bit set)
^ *Π (file has setuid bit set)
^ *  >/  (file descriptor is standard output)

| 

            "&


Yombining conditions

^ It is possible to combine conditions by using following operators:

^ * (logical AND operator)


^ * (logical OR operator)
^ ! (logical NOT operator)

| 

            "'


Yombining conditions

^ The syntax for this is:

   > -   >E


)
A   > -   > B

   > -   >E


)
A  > -  > B

  C   > ) A C   > B

| 

            "(


Yombining checking in scripts

^ Bash shell provides the  command to test if a condition. The


general format of this command is:

 /
 
/


^ The / is typically formed using the   command.

| 

            #


Example

^ # to check if the current directory is the same as your home


directory
curdir=`pwd`
if test ³ùcurdir´ != ³ùHOME´
then
echo your home dir is not the same as your
present working directory
else
echo ùHOME is your current directory
fi

| 

            #


Yhecking multiple conditions

The complex form of  statement is as follows:

 />
 
/
 />
 
/

/


| 

            #


ising for loop

^ The Bash shell provides a  loop. Example:


^ for  in 1 2 3 4
The syntax of this loop is: 5
do
 variable  list echo ù
/
echo ³`expr ù \u ù`´
command
done
F
command
/

| 

            #"


Example

----------------------script.sh--------------------------
#! /bin/sh
usernames=`who | awk {print ù1}`
echo ³Total users logged in = ù#usernames´
#
for user in ù{usernames}
do
echo ùuser
done
------------------------------------------------------------

| 

            ##


ising while loop

^ The Bash shell provides a Ñ loop. The syntax of this loop is:

Ñ condition
/
command
F
command
/

| 

            #$


Example

^ Shell script checks for a blank/non blank string


eg: read nam
while [ -z ³ùnam´ ]
do
echo ³\c´
read nam
done
echo the string is ùnam
the above piece of code keeps accepting string variable nam until
it is non zero in length.

| 

            #%


Switch-case statement

- THE CASE STATEMENT


case value in
pattern1)
command
command;;
pattern2)
command
command;; «
patternn)
command;;
esac

| 

            #&


Example
echo enter a choice
read choice
case ùchoice in
1) echo enter 2 nos
read num1
read num2
res=`expr ùnum1 + ùnum2`
echo result is ùres;;
2) who;;
u) echo invalid choice;;
esac

| 

            #'


riting functions

^ Shell functions are a way to group commands for later execution


using a single name for the group. They are executed just like a
"regular" command.

^ Shell functions are executed in the current shell context; no new


process is created to interpret them. Functions are declared
using this syntax:

A Π B  GH I /*: J

| 

            #(


Debugging shell scripts

^ At times you may need to debug a program to find and correct


errors. Two options to the sh command can help you debug a
program:

sh -v shell_script_name

^ The ³-v´ (verbose) option prints the shell input lines as they are
read by the system.

| 

            $


Debugging shell scripts

sh -x shell_script_name

^ The ³-x´ (execute) option prints the commands and their


arguments as they are executed.

^ To try these two options, create a shell program that has an


error in it.

| 

            $


ïrogramming in Y vs Shell

Comparison between
^ A solution in C

^ A shell solution written like a C pgm

^ A proper ³shell/unix´ solution

e.g:
The problem is to count the no of lines in a file ( the file is
called the_file)

| 

            $


A solution in Y A shell solution

#include <stdio.h> count=0


void main(void) while read line
{ do
int lcount=0; count=`expr ùcount + 1`
FILE uinfile; done < the_file
char line[500];
infile=fopen("the_file","r");
echo Number of lines is ùcount
while(!feof(infile))
{
fgets(line,500,infile); Solution using existing
lcount ++;
}
commands
printf("no of lines is %d\n",lcount);
} $ wc ±l the_file

| 

            $"


i IX Oibliography

^ i  m    , Paul W. Abrahams & Bruce R. Larson


(Addison-Wesley Publishing Company, 1992, ISBN 0-201-
55703-7). (
^ i 
 m 
m m
m (O'Reilly & Associates, Inc., 1990, ISBN 0-937175-20-
X). (A handy reference for BSD.)
^ i 
 
m m    !
 m"# (O'Reilly & Associates, Inc., 1992, ISBN 0-56592-
001-5). (A handy reference for SysV and Solaris 2.)
^ Ôi $m %m %&m   , Brian W. rernighan &
Rob Pike (Prentice Hall, 1984). (A classic. For serious folks.)

| 

            $#


Lab Exercises

| 

            $$


| 

            $%


| 

            $&


| 

            $'


| 

            $(


Ôhank You

| 

            %

Potrebbero piacerti anche