Sunteți pe pagina 1din 66

A shell is a piece of software that provides

an interface for users of an operating system which


provides access to the services of a kernel.

The primary purpose of the shell is to invoke or "launch"


another program; however, shells frequently have
additional capabilities such as viewing the contents of
directories.
THOMPSON SHELL
 The Thompson shell was the
first Unix shell, introduced in the
first version of Unix in 1971, and
was written by Ken Thompson.
 Simple command interpreter
 Not designed for scripting
 Introduced several innovative
features to the command line
interface
 Led to the development of the
later Unix shells.
KEN THOMPSON
FEATURES OF THOMPSHON
SHELL
 An early feature of the Thompson shell was a compact
syntax for input/output redirection

 One could simply add an argument to the command


line consisting of the < symbol followed by a filename
for input or the > symbol for output, and the shell
would redirect I/O for the duration of the command.
FEATURES OF THOMPSON SHELL…

 A later addition was the concept of pipes. At the


suggestion of Douglas McIlroy, the redirection syntax
was expanded so that the output of one command
could be passed to the input of another command.
CRITICISM OF THOMPSON SHELL
 The shell's design was minimalistic.
 even the if and goto statements, essential for control of
program flow, were implemented as separate
commands.
 As a result, by the 1975 release of Unix Version 6, it was
becoming clear that the Thompson shell was
inadequate for most serious programming tasks.
BOURNE SHELL (sh)
 The Bourne shell, or sh, was
the default Unix shell of Unix
Version 7.
 Replaced the Thompson
shell.
 It was developed by Stephen
Bourne, of AT&T Bell
Laboratories, and was
released in 1977.

STEPHEN BOURNE
FEATURES OF BOURNE SHELL

 Its command interpreter contained all the features


that are commonly considered to produce structured
programs.

 Although it is used as an interactive command


interpreter, it was always intended as a scripting
language.
 To provide programmability including control flow and
typeless variables.

Looping Constructs
1. Until
2. While
3. For

Conditional Constructs
1. If
2. Case
 To allow shell scripts to be used as filters.

 Control over all input/output file descriptors.

 No limits on string lengths when interpreting shell


scripts.
 Shell 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:


[ function ] name () { command-list; }
 The environment mechanism.
This allowed context to be established at startup and provided a way
for shell scripts to pass context to sub scripts (processes).

Environments can affect how programs run, so it's very important


that they cannot inadvertently affect one another.
Whenever a new (sub)process is started, it has its own CEE and
environment.
Of course you would not want it to be completely empty;
Also, If all your existing variables ended up in the environment of
your subprocess you might adversely affect the running of the
program that you started in that subprocess.
The compromise between the two extremes : a subprocess has an
environment which contains copies of the variables in the
environment of its parent process — but only those variables that are
marked to be exported (i.e. copied to subprocesses).
Here's an example of the distinction:
Exported and non-exported variables

$ echo $PATH
/usr/local/bin:/usr/bin:/bin
$ VAR=value
$ echo $VAR
Value

$ sh
$ echo $PATH
/usr/local/bin:/usr/bin:/bin
$ echo $VAR
$
In the example above, the PATH variable (which is marked for export by default) gets copied into the
environment of the shell that is started within the shell. But the VAR variable is not marked for
export, so the environment of the second shell doesn't get a copy.
 Rationalize and generalize string quoting mechanism.
Special Characters
Below are the characters that are special to the Bourne shell Quoting
these characters turns off their special meaning
#&*?[]()=|^;<>`$"'\
How Quoting Works
 ' xxx ‘ Disable all special characters in xxx .

 " xxx “ Disable all special characters in xxx except $ , ` , and \ .

 \x Disable special meaning of character x . At end of line,


a \ removes the newline character (continues line).
 Scripts can be invoked as commands by using their
filename
 Allow both synchronous and asynchronous execution of
commands
 supports input and output redirection
 pipelines
 provides local and global variable scope
 scripts do not require compilation before execution
C - SHELL (Csh)
 Is a Unix shell that was created
by Bill Joy while a graduate
student at University of
California, Berkeley in the late
1970s

 The C shell is a command


processor that's typically run in
a text window, allowing the user
to type commands which cause
actions. The C shell can also
read commands from a file, BILL JOY
called a script.
 The Unix system had been written almost exclusively
in C, so the C shell's first objective was a command
language that was more stylistically consistent with the
rest of the system.
 ie., the intent for writing the C shell was to create a
shell with C language-like syntax.
 The keywords, the use of parentheses and the C shell's
built-in expression grammar and support for arrays
were all strongly influenced by C.
The second objective was that the C shell
should be better for interactive use.
In support of that, it introduced numerous
new features that made it easier, faster and
more friendly to use by someone sitting at a
terminal, typing commands. Users could get
things done with a lot fewer keystrokes and it
ran faster. The most significant of these new
features were
Features of C-Shell
 History
History allows users to recall previous commands and
rerun them by typing only a few quick keystrokes.
For example, two exclamation marks, "!!", typed as a
command and referred to as "bang, bang,"means run
the immediately preceding command.
 Aliases
Aliases allow the user to type the name of an alias and
have the C shell expand it internally into whatever set
of words the user has defined.
For many simple situations, e.g., running the "fgrep"
command by typing "f", it runs faster and it's more
convenient than creating a script
 Directory stack
The directory stack allows the user to push or pop
the current working directory, making it easier to jump
back and forth between two different places in the
filesystem without having to do much typing.
 Tilde notation
Tilde notation offers a shorthand way of specifying
pathnames relative to the home directory using the "~"
character.
 Interactive filename completion
The escape key could be used interactively to show
possible completions of a filename at the end of the
current command line.
 Cdpath
Cdpath extends the notion of a search path to
the cd (change directory) command: If the specified
directory isn't in the current directory, csh will try to
find it in the cdpath directories.
 Job control
Under sh, a user could only do one thing at a time. A user
who started to edit a file had to finish or at least save his
work and get out before doing anything else. A user
couldn't simply open another window. The C shell's job
control solved that by allowing the user to suspend the
current activity and create a new instance of the C shell,
called a job, by typing ^Z. The user could then switch back-
and-forth between jobs using the fg command. The active
job was said to be in the foreground. Other jobs were said
to be either suspended (stopped) or running in the
background.
 Path hashing
Path hashing speeds up the C shell's search for
executable files. Rather than doing filesystem calls in
each path directory, one-at-a-time, until it either finds
the file or runs out of possibilities, the C shell consults
an internal hash table built by scanning the path
directories. That table can usually tell the C shell
where to find the file, if it exists, without having to
search, and can be refreshed with the "rehash"
command.
 Command line shortcuts
Here are a few keys which may be pressed to perform
certain functions.
<escape>: The escape key preceded by a partial command
or filename will attempt to complete the filename. If there
are more than one filename matching, the common letters
are completed, and the C shell beeps.
Control-D: When typed after a partial filename, C shell
gives a list of all matching filenames or commands.
Control-W: Erases over the previous word.
Korn Shell (Ksh)
 Invented by David Korn of AT&T Bell Labs in mid
1980s
 Upwardly compatible with the Bourne shell
 Became a standard part of Unix Systems Labs (USL)
SVR4
 Two major versions exist, ksh88 and ksh93
.profile
 Kept in your home (login) directory
 Used for customizing the user interface of ksh
 Used to store
 Aliases
 Shell variables
 Options
 Location of environment file
 Only executed if ksh is a login shell
Command Line Editing
 Enabled in two different ways
 Using the shell variable VISUAL
 VISUAL=$(whence vi)
 Using set option
 set -o vi
 Two different editors are available
 vi and emacs
 Note: ksh does not use these editors, it has commands
that emulate the functionality built in to the shell
File Name Completion in vi-mode
 File name completion is also supported
 Type the command and the beginning of the file name
 Touch ESC and the \
 ksh will attempt to complete the file name for you
 If no name matches, shell beeps and nothing happens
 If there is exactly one way to complete the name, the shell
does it, if it's a directory, it adds a /
 If there are more than one match, the shell completes the
longest common prefix
 Using * instead of \ lists all matches
History
• This feature alone may make it worth
moving to Korn shell (when combined with
command line editing)

• History is stored in a file (normally


.sh_history) in your home directory
– Location can be changed by defining HISTFILE
– Size is set by HISTSIZE - default is 128
Using History with Korn
 Korn shell:
 $r 36 (to re-execute command 36 in history)
 $r f (to re-execute the most recent command
beginning with f)
 $fc f (to fix command that started with an f)
or $fc cmd_no.
 This will put you into the editor of your choice (defined by
FCEDIT - default is ed!)
 When you leave the editor, the command will be executed
 $fc –l (lists history commands)
 ksh automatically aliases history to fc -l

32
Environment File
 Although predefined environmental variables will
always be known to subshells, the shell must be
explicitly told which other variables, aliases, and
options should be communicated to subshells
 One way to do this is to put them in an environment
file
 Do this by placing
 export ENV=~/environmentfile in your .profile and then
putting your data in environmentfile

33
Random Numbers
 The Korn shell provides a random number generator
 To initialize it, you type RANDOM=$$ (or a specific
number if you want a repeatable sequence)
 Each time you echo the RANDOM variable, you will
get anew random number in the range 0 -32767

34
print
 In other shells, you usually use awk when you want
formatted printing
 ksh provides print. It doesn't allow as much control
over printing as awk but it does provide more control
than echo
 print has a variety of formatting options and
parameters

35
print Formatting Options
 \a - announce, ring the bell
 \b - backspace
 \c - print line without newline (rest of args ignored)
 \f - formfeed
 \n - newline
 \r - carriage return
 \t - tab
 \v - vertical tab
 \Ox - the 8 bit ASCII character with octal value x
 \\ - backslash

36
whence
 Tells you where a command resides
 Two options, -p and -v, control the format of the output
 whence alone prints the path to the command
 whence vi
 /bin/ucb/vi
 -v also lists the type of command
 whence -v vi
 vi is a tracked alias for /usr/ucb/vi
 -p does a path search even if the name is a reserved word or
alias

37
Built-In Arithmetic
 ksh lets you do arithmetic using either the let
command or (( ))
 (( )) good for True/False comparisons; $(( )) provides
value of computation
$ let a = 6+8
$ print $a
$ 14
 Note that there are no spaces in the expression. If you
want to use spaces, you must single quote the expression

38
 The (( )) is useful in as a conditional because it returns
a 1 or 0
if test (($min+$max>$top))
then
print "Ooh, a big one!"
else
print "Guess not"
fi

39
Aliases
 ksh has aliases very similar to the C shell
 It adds the concept of tracked aliases
 These translate faster than normal aliases
 When used, the shell searches the path the first time
and then remembers where the command was found
 Future uses of the alias go directly to the command
 You can also unalias in the Korn shell

40
Job Control
 Korn shell supports job control almost the same as C shell
 CTRL-Z places a job in the background, as does command
&
 fg brings a job back to the foreground
 Referring to background jobs is also similar
 %n job n
 ?string job whose command contains string
 %+ most recently invoked background job
 %% same as %+
 %- second-most recently invoked bg job

41
Additional Pattern Matching
 Korn shell supports additional pattern matching
metacharacters
 ?(pattern[|pattern]…) matches zero or one occurrence
of any of the patterns
 phre?([drs]|xx) would match phred, phrer, phres, and
phrexx.
 *(pattern[|pattern]…) matches zero or more
occurrences of any pattern
 phre*([0-9]) would match 'phre' or 'phre' followed by
any number of digits

42
 +(pattern[|pattern]…) matches one or more
occurrences of any pattern
 phre+([0-9]) would match 'phre' followed by one or
more digits, +(x) would match 'x', 'xx', 'xxx' …
 @(pattern[|pattern]…) matches any occurrence of any
pattern
 Most useful when used as a logical OR.
phre@(ddy|ds|ak) would match phreddy or phreds or
phreak. @(x|y|z) matches 'x' or 'y' or 'z'

43
Typeset
 In the Korn shell, you can assign types to variables
 typeset -i count
 makes count an integer, if you tried to assign a string to
it, the shell would give you an error message
 You can typeset with the following attributes
 -u make uppercase (forces string to uppercase)
 -l make lowercase
 -in require integers and store internally as integer;
n specifies the base
 -r make variable readonly
 -xexport the variable
44
 -Ln left justify to remove leading spaces; fill with
spaces or truncate on right to n bytes
 -Rn right justify to remove trailing spaces; fill with
spaces or truncate on left to n bytes
 -Zn same as -R except pad with leading 0's instead
of spaces
 typeset +o is used to turn the option off

45
Functions
 The Korn shell's function feature is an expanded version of
that found in the Bourne shell
 A function is similar to a script except it is kept in the
shell's memory. Because it is kept in memory, it runs faster
than loading a script
 Functions allow you to create your own groups of
commands, which can make shell programming much
easier since they can be used analogously to subroutines
 Functions are not inherited by subshells unless you define
them in the environment file with the typeset command:
typeset -fx functname
46
Syntax
function functname{
shell command
shell command

}

 You can delete a function using unset -f functname


 You can find out what functions are defined using the
command (actually an alias) "functions"
 The shell will print the names and definitions of all functions

47
 There are two important differences between
functions and scripts
 A functions does not run as a separate process
 It shares variables with the process that invoked it
 The present working directory is that of the caller
 If the function changes it, it will also be changed for the caller
 If a function has the same name as a script or executable
program, the function takes precedence
 The return statement returns the exit status of the last
command executed
 Functions can be recursive but you need to be careful

48
 The Korn shell's major other features include:
 Integrated programming features : the functionality of
several external UNIX commands,
including test , expr , getopt , and echo , has been integrated
into the shell itself, enabling common programming tasks to
be done more cleanly and without creating extra processes.
 Debugging primitives that make it possible to write tools
that help programmers debug their shell code.
 Regular expressions , well known to users of UNIX
utilities like grep and awk , have been added to the standard
set of filename wildcards and to the shell variable facility.
 Advanced I/O features , including the ability to do two-
way communication with concurrent processes
( coroutines ).
 Increased speed of shell code execution.
 Security features that help protect against "Trojan horses"
and other types of break-in schemes.
 In spite of its increased size, ksh provides better
performance. You can write programs to run faster with
ksh than with either the Bourne shell or the C shell,
sometimes an order of magnitude faster.
 ksh is compatible with the Bourne shell. Virtually all
programs written for the Bourne shell run with ksh.
TCSH
 a Unix shell based on and compatible with the C
shell (csh).
 It is essentially the C shell with programmable command
line completion, command-line editing, and a few other
features.

 The 't' in tcsh comes from the T in TENEX, an operating


system which inspired Ken Greer at Carnegie Mellon
University, the author of tcsh, with its command-
completion feature.Ken Greer began working on his code
to implement Tenex-style file name completion in
September 1975, finally merging it into the C shell in
December 1981.
FEATURES
 Command line completions
 An important feature that is used by almost all users of a shell is
the command line completion. With this feature you don't need to type
all the letters of a filename, but only the ambiguous ones. This means
that if you wish to edit a file called file.txt, you may only need to
type fi and hit the TAB key, then the shell will type the rest of the
filename for you.Basically one can complete on files and directories.
This means that you can not complete on host names, process id's,
options for a given program etc. Another thing you can not do with this
type of completion is to complete on directory names only, when
typing the argument for the command cd
 In TCSH, the completion mechanism is enhanced so that it is possible
to tell TCSH which list to complete from for each command. This
means that you can tell TCSH to complete from a list of host names
when completing on the commands rlogin and ping. An alternative is
to tell it to complete only on directories when the command is cd.
 Command-line Editing
Like the Korn shell, tcsh provides an emacs and vi
command-line editing mode
Selected by "bindkey -e" of "bindkey -v" command
Generally placed in your ~/.tcshrc file
One advantage over Korn shell editing is that you
are always in the command-line editor!
Normal mode is insert, which is how you enter
commands
Various editing commands are available in insert
mode
 History
The history mechanism of the shell is a valuable thing, which makes it
easier to type similar commands after each other. To see a list of the
previously executed commands, type history.
The following lists the event specifiers:
!n: This refers to the history event, with index n
!-n: This refers to the history event, which was executed, n times
ago
!-1 : for the previous command,
!-2 : for the one before the previous command etc.
!!: This refers to the previous command

“With these commands, you can re-execute a command. E.g. just


type !!, to re-execute the previous command. “
 Patterns
Tcsh has the opportunity to type all these files for you, with file
patterns. The following list shows which possibilities there exists:
*Match any number of characters
?Match a single character
[...]Match any single character in the list
[x-y]Match any character within the range of characters from x to y
[^...]Match elements, which does not match the list
{...}This expands to all the words listed. There's no need that they
match.
^...^ in the beginning of a pattern negates the pattern.
Examples
Match all files ending with .tex*.texmatch
 Aliases
When using the shell one will soon recognize that
certain commands are typed again and again.
Example. The one at top ten is surely ls –la.
TCSH has a mechanism to create aliases for
commands. This means that you can create an alias
for ls -la just called la.
 Repeating Commands in a Loop
If you want to run a command once for each of a
set of filenames, you can use a foreach loop
$ foreach fn ( file1 file2 file3 file4)
? cat $fn | spell > $fn.spl
? end
After you enter the foreach line, the shell changes the
prompt as it collects the body of the loop and then
executes it after the end is entered
 Word Completion
In csh if filec is set, it will attempt to complete
filenames for you when you hit the TAB key
If the prefix you type is ambiguous, CTRL-D will list all
potential matches
In tcsh, command completion is always active
To exclude certain filename suffixes from being
considered, set fignore = ( .o .bak ) in your
~/.tcshrc file
 Spelling Correction
To enable spelling correction, add one of the following
to ~/.tcshrc
set correct = cmd
set correct = all
The first option causes spelling correction to be
applied for commands only.
The second tries to correct all entries on the
command line.
You need to be careful with correct = all
 Directory Stacks
Moving between two directories in tcsh is simple "cd -"
returns you to your previous directory .For more control
with multiple directories, both csh and tcsh allow a
directory stack
pushd and popd, along with dirs are used with the stack:
pushd dirname changes to that directory and
pushes the directory onto the stack
popd changes to the directory on the top of the stack
dirs lists the contents of the stack without changing your
current directory.
Bourne Again Shell (BASH)
 Bash is a Unix shell. The name is an acronym,
a pun and descriptive. As an acronym, it stands
for Bourne-again shell, referring to its initial
conception as a free open source clone of
the Bourne shell (sh).As a pun, it refers to the
Christian concept of being born again. The name is
also descriptive of what it did, bashing together the
features of sh, csh and ksh.
Little History
 Brian Fox began coding Bash on January 10, 1988
after Richard Stallman became dissatisfied with the lack of
progress being made by a prior developer. Stallman and
his Free Software Foundation (FSF) considered a free shell
that could run existing sh scripts so strategic to a
completely free system built from BSD and GNU code that
this was one of the few projects they funded themselves,
with Fox undertaking the work as an employee of FSF. Fox
released Bash as a beta, version .99, on June 7, 1989 and
remained the primary maintainer until sometime between
mid-1992 and mid-1994, when he was laid off from FSF and
his responsibility was transitioned to another early
contributor, Chet Ramey.
PREVIOUS YEAR QUESTIONS
 Explain different types of shells in Linux. Write a shell
script to generate Fibonacci series?
(2008, 10)
 Discuss the features of bash and sh shell in Linux.
(2006, 10)
 What are different types of shells available in Linux?
Explain. (2003, 4)
 Define different types of shell in Linux? Differentiate
among them. (2002,4)
 Differentiate between the following with example.
(b) BASH and TCSH (2001, 2.5)
BIBLIOGRAPHY
 http://en.wikipedia.org/wiki/Bash_(Unix_shell)#Features
 http://linuxgazette.net/issue12/tcsh.html
 http://en.wikipedia.org/wiki/C_shell
 http://www2.research.att.com/~gsf/download/
 http://kornshell.com/software/
 http://www2.research.att.com/sw/download/man/man1/k
sh88.html
 http://www.cs.utah.edu/dept/old/texinfo/bash/features.ht
ml#SEC1
And many more…
Amrita Upreti
MCA – IV
02311604409
BVICAM

S-ar putea să vă placă și