Está en la página 1de 31

Shell programming

Introduction
If we divide the UNIX operating system we find that there are three distinct divisions
namely the Kernel, the shell and tools and utilities.
The Kernel is the control operating system program of UNIX that supports and co-
ordinates all other programs and controls all physical resources. Tools and utilities are
small independent programs that allow you to perform various functions. A shell is a
user program much like any other program (i.e., tools and utilities ) in the UNIX
operating system.
This program plays a role of an interpreter when two persons are trying to
communicate with each other in two different languages, or works like a compiler that
communicates between a user using some higher level language and the machine that
only understands the machine level language. The shell program interprets that what
you type as a command request and then locates and executes the program that will fulfill
your request.
The shell is not just a collection of commands but a really good
programming language. You can automate a lot of tasks with it, the shell is very
good for system administration tasks, you can very quickly try out if your ideas work
which makes it very useful for simple prototyping and it is very useful for small utilities
that perform some relatively simple tasks where efficiency is less important than ease of
configuration.
WORKING OF A SHELL
The shell provides the necessary interface between you as a system user and the
kernel program.
when you type a command on your keyboard it is the shell program that interprets
what you have typed as a command. It then understands the command as a request to
run or execute the required command program. The shell the searchers the necessary
program by using the path described in the profile file. If the program is not available
in any of the directories specified on the path a warning message is simple displayed
conveying you its inability to find the program. The message is then followed by the shell
prompt.
if it finds the program, it brings the program into the memory and executes it after
the successful execution of the program, again the shell prompt appears. The shell thus
acts as command interpreter.
Though, in interpreter, it operates at the same level as any other command program
such as date, who, etc., when these command programs run, they replace the shell, and
when the commands finish, the shell returns once again to replace them.
Although not a part of the UNIX system kernel, a shell uses much of the UNIX
system kernel to execute program, create files and co-ordinate execution of more than
one programs running simultaneously.
Command file
The reading of the kernel program (/UNIX ) into the computers memory and its
execution is followed by the initialization of the process table. The init process is then
created that overseas the creation of the processes. This init process causes the login
prompt to appear on your monitor on successful logging in the login. Shell prompts the
user, to interact with system, by typing commands, by displaying the dollar ($) sign.
we define command as a unit of conversation between the user and the shell.
Syntactically, a command is a string of one or more characters that ends with a new line
character.
TYPES OF SHELLS
The shell runs like any other program under UNIX system. Hence one shell program
can replace the other, or call another shell program as it would call any other program,
due to this feature, a number of shells have been developed in response to different needs
different needs of users. Some of the popular shells are listed below.
BOURNE SHELL :
This is the original command processor developed at AT & T, after developer,
Stephen R. Bourne. This is the official shell that is distributed with UNIX systems. The
Bourne Shell is the fastest UNIX command processor available and can be used on all
UNIX systems. The Bourne Shell is the most widely used shell at present. The executable
filename is sh.

C SHELL :
This is another command processor developed by William Joy and others at the
University of California at Berkeley and gets its name from its programming language
which resembles the C programming language in syntax. The executable filename is csh.
KORN SHELL :
Developed by David Korn, this combines the best features of both the above
shells. Although very few systems currently offer this shell, it is slowly gaining
popularity. The executable filename is ksh.
RESTRICTED SHELL:
This is a restricted version of Bourne Shell. It is typically used for guest login-
users who are not part of the system and in secure installations where users must be
restricted to work only in their own limited environments. The executable filename is rsh.
TC SHELL TCSH:
This shell is available in the public domain. It provides all the features of the
Cshell together with EMACS style editing of the command line.
BOURNE AGAIN SHELL BASH:
It is intended to be a full implementation of the IEEE posix Shell and Tools
specification. This shell is widely used within the academic community.
Bash provides all the interactive features of the C shell (csh) and the Korn shell
(ksh). Its programming language is compatible with the Bourne shell (sh).
If you use the Bourne shell (sh) for shell programming consider using bash as
your complete shell environment.
Summary of shell facilities

Bourne C TC KORN BASH

Command history No yes Yes Yes Yes


Command alias No yes Yes Yes Yes
Shell scripts Yes yes Yes Yes Yes
File name completion No yes Yes* Yes Yes*
Command line editing No yes No Yes Yes*
job control No yes Yes Yes Yes

* Not the default setting for this shell

Which Shell to Use?


The Bourne Shell
Has the following advantages over the C and Korn Shells:
The standard AT&T shell-it is found on almost all UNIX systems
Compact and require minimal resources
Executes quickly
Widely accepted (portable scripts)
The file profile located in your home directory is executed each time you login
if you are using the Bourne (and Korn) Shell. You can customize your default working
environment by placing environmental definitions in this file.
The C Shell
Includes the following features which make it more suitable for interactive
applications than the Bourne shell:
Extended Setup Files
* .login
* .cshrc (set, history, and alias commands)
*.logout
Command Alias
Command History
Process (job) Control (BSD only)

Script Syntax Similar to C Language


Unfortunately the script language of the CShell is not compatible with Bourne and
Korn Shells.
The Korn Shell
is compatible with and includes most of the features of the Bourne shell. It also
includes interactive features analogous to those of the Cshell
THE SHELL VARIABLES
A Variable can be defined as a quantity that can take on different values. We
can call a variable as a kind of storage place for a value.
we can extend this general definition of a variable to our concept of shell. Value
that is known to your Shell program is called the Shell variable The Quantity
assumes the specific value only as far as the particular shell program is concerned.
Outside that program. The value will vary. Thus for example in one shell program we
may assign say value 2 to the variable X, while in second program we may equate X to
any other value. The first program therefore knows X by its value 2, while second
program will know X by value, probably other than 2.
There are three types of variables
1. User Variables
2. Shell Variables
3. Read-only User Variables

The Bourn Shell has no true numeric variables. It uses string variables to
represent numbers, as well as text. String variables are able to take on the value of a
string of characters. There are three types of variables in the Bourn Shell. They are user
variables, Bourne Shell variables, and Read-only user variables.
you can declare, initialize, read, and modify user variables from a Bourn Shell
script or from the command line. The Bourne Shell itself declares and initializes shell
variables, but you can read and modify them, The Bourne Shell also initializes the read-
only variables, and you can read but not modify.
User Variables
It is legal to assign any sequence of non-blank characters as the name of a
variable . The example below creates a variable called person and initializes it with the
string SURANA
It is important to note that you must NOT precede or follow the equal sign with a
space or TAB character.
Example:
$person=SURANA
This example indicates that person does not represent the string Richard. The
string person is echoed as person. The Bourn Shell will only do the substitution of the
value of the variable when the name of the variable is preceded with a dollar sign ($).
Example:
$ECHO PERSON
Person
$echo $person
SURANA
$
If you want to have imbedded space in a variable, it is necessary to quote the
string.
Example:
$person=SURANA and College
$echo $person
SURANA and College
$
The echo utility copies its arguments to the standard output. The command echo $person
displays the value of the variable person. It will not display $person because the Bourne
Shell doesnt pass $person as an argument.

The leading dollar sign ($) causes the Bourne Shell to substitute the value of the variable
and then passes that value to the utility. The echo utility then displays the value of the
variable, not its name, never knowing that you called it with a variable. The Bourne Shell
passed the same command line as if you had typed in echo SURANA and College. The
Bourne Shell can be prevented from doing this substitution by entering one of the
following:
Example:
$echo $person
SURANA and College
$
In this session the contents of the variable person are displayed. The Bourne Shell
made the substitution because the variable name person is preceded by a dollar sign ($).
$echo \$person
$person
$
In the above example the variable person is preceded by a dollar sign ($) but the
dollar sign has a backslash (\) ahead of it. The backslash has the effect of canceling the
special meaning of the character following the backslash. In this case, the special
meaning of the dollar sign is ignored and the substitution is not done.

$echo $person
$person
$
The single quote marks () causes the characters between the marks to be taken as
literal. The shell makes no attempt to interpret the meanings of these characters. The shell
passes these characters on with no substitution.
$echo $person
SURANA and College
$
The double quote marks do not prevent the shell from making substitution; and
the value of the variable will be displayed by the utility.
Shell Variables
The Bourne Shell declares and initializes variables that determine such things as
your home directory, what directories the shell will look in when you give commands,
how often to look for mail, your prompt, and many other things. We will look at these
Bourne shell variables and their functions. You can assign new values to these variables
from the command line or from the execution of the profile in your home directory.

HOME
The first Bourne shell variable that we will look at is the HOME variable. By default,
the home directory is the current working directory after you login. The system
administrator determines your home directory when you establish an account and places
that information in the /etc/passwd file. When you login , the Bourne shell gets that
pathname and assigns it to the HOME variable.
when you enter a cd command with no argument, the utility takes the name of the
directory from the HOME variable to another directory pathname, the utility will make
the new directory the current working directory.
Example:
$echo $HOME
/uscr0/srik
$cd
$pwd
/user0/srik
$HOME=/user0/srik/mca
$cd
$pwd
/user0/srik/mca
$
This example shows how the value of the home variable effects the ed utility. The ed
command will use the value of the home variable as the pathname for the current working
directory.
IFS
This is the internal field separator Bourne shell variable. You can always use a space or
tab to separate characters on the command line. When you assign the IFS character , you
also use this character as the field separator.
Example
$num _ args a : b : c : d
This example shows only one argument, namely a : b : c : d.
$IFS=:
$num_args a : b : c : d
This e3xample now shows four different arguments ;each being separated by the new IFS
, (:) .
MAIL
The mail variable contains the name of the file that the mail (and mailx )utilities used to
store your mail. Usually, the absolute pathname of this file is / usr/mail/name, where
name is your login name.

Example:
$MAIL=/ usr / mail / srik
MAIL PATH
This variable contains a list of filenames separated by colons. If set , the Bourne shell will
inform you when any of these files are modified (i.e. when new mail arrives.).
Normally, this variable is not set.
MAIL CHECK
This variable specifies how often , in seconds the Bourne shell will check for new mail.
The default is 600 seconds. If sety to 0, it will check for new mail each time before it
gives you a prompt.
PATH
This Bourne shell variable will describe the directories that will be searched looking for
the program that you want to execute. The Bourne shell looks in several directories for a
file that has the same name as the command that you entered. The PATH variables
controls this search path. Normally, the first directory searched is the current working
directory. If the program is not found , the search continues in the /bin and then the /usr /
bin directory.
Generally, these directories contain executable programs. if the program is not found in
one of these directories, the Bourn Shell reports that the program cant be found (or
executed).

The PATH variable lists the pathnames in the order in which the search will
proceed. The pathnames are separated by a colon (:). If nothing (null string) precedes the
colon, that indicates to start the search at the current working directory.
Example:
$path=:/user0/strik/bin:/usr/bin
$
This PATH variable indicates to start the search for the program at the current
working directory, then look in the directory /user0/srik/bin,then /bin, and finally
/usr/bin.
If each user has a unique path specified, each user can execute a different program
by giving the same command. The search for the program stops when it is satisfied: thus,
you can use the same name for your own programs as the standard UNIX utilities. To do
this, simply put your program in one of the first directories that the Bourne Shell
searches.
PSI
This is the Bourne Shell prompt which lets you know that the shell is waiting for
you to give it a command. The default Bourne Shell prompt is a dollar sign ($). The shell
stores the prompt as a string variable in PSI. When you change the value of this variable,
the appearance of the prompt will change. When you are working on several different
machines, it might be useful to have the prompt be the name of the machine you are
working on.
Example:
$pwd
/user0/srik
$PSI=BCA:
BCA:
Notice that prompt is now BCA:
PS2
This variable is called the secondary prompt. If the command is not completed on
one line and must be continued on the next line, the prompt for that continued line is PS2.
The default is >. This prompt indicates that the Bourn Shell is expecting you to finish the
previous command line.
Example:
$echo demonstration of prompt string
>2 and display
demonstration of prompt string
2 and display
$PS2=Continue?
$echo demonstration of
Continue? Prompt string2 and display
demonstration of
prompt string2 and display
$
Notice how the secondary prompt was changed to Continue?

Read-Only User Variables


The contents of the user variables and the shell variables can the shell variables
can be modified by the user. It is possible to assign a new value to them. The new value
can be assigned from the dollar (#) prompt of from inside a Bourne Shell script. Read-
only variables are different. The value of read-only variables can not be changed.
The variable must be initialized to some value; and then, by entering the
following command, it can be made read only.
Command format: readonly variable-name
variable_name= of the variable to be made read only
Sample Session:
$person=Kathleen
$sreadonly person
$echo $person
Kathleen
$person=Richard
person : is read only
$
The readonly command given without any arguments will display a list of all the
read-only variables.
Example ;
$person=Kathleen
$readonly person
$example=Richard
$readonly example
$readonly
readonly person
readonly example
$
SHELL SCRIPTS
So far, we have only seen examples where Unix commands were simply typed at
the terminal to the $ prompt. In this topic we will see examples where the Unix
commands are stored in a file and are executed again and again without our having to re-
type them. When we have put some commands into a file, we can use the name of the file
as a new command. This means that we can create our own commands which work like
the built-in commands we saw in earlier chapters. An executable file containing Unix
commands is called a shell script, or simply, a script. Shell scripts are one of the most
powerful and useful facilities of Unix.
Our very first script
This command puts some text into a file called newcmd:
$ cat > newcmd
date
pwd
Is
^D
$
Putting text in a file is best done with vi or one of the other Unix editors.
However, for very small files, using cat and output redirection is simpler.
Now we have created the file, we can display it:
$more newcmd
date
pwd
Is
$
As you can see, it contains three Unix commands, one per line.
we can now execute the commands in newcmd by entering this command:
$ sh newcmd
Mon Mar 13 11:25:42 BST 2003
/usr/bin/srik
bca.sh
mca.sh
chaper1
chapter2
chapter3
chapter4
newcmd
$
Notice that the three commands are executed in the order in which they occur in
the file. Also, note that the output from the three commands is joined together; unless we
know what output to expect, we cannot tell which lines are from which command . In
fact, the first line of output is from the date command, the second is from pwd and the
remaining are from is.
By default, any file created by UNIX does not have execute permission. This
means that, until the permission have been changes, the file can not be directly executed
by typing the filename at the $ prompt.
Alternatively, a file can be executed by using the sh command. For example, to
execute a script called newcmd, the command is:
$ sh newcmd
This creates a new shell which takes the specified filename as a parameter and
executes it. Once the execution is completed the shell dies and returns to the $ prompt
again.

In order to execute the shell script directly at the $ prompt, we can change the File
Access Permission of the specified filename by granting the execute permission. Once
the execute permission is granted, the shell script can be executed by directly invoking its
name at the $ prompt. For Example.
$ chmod u+x newcmd
$ newcmd
The above command grants the execute permission to the user and executes the
script.
Shell is a complete programming language
Readers who have already learned a programming language may like to know that
all the facilities you would expect to find in a programming language exist in the shell
language. The difference between a shell script and an ordinary program is that:
A program contains instructions for the computers CPU to execute but a script
contains instructions for Unix to execute;
A programs smallest step is one statement but a scripts smallest step is one Unix
command.
Programs and scripts both provide the following facilities:
Sequences of commands
A means of switching from one file to another
Parameters
Global variables
Local variables

Selection control structures


Repetition control structures
Procedures
Recursion
a means of output
A means of input
Comments
White space blank lines and indentation
ECHO COMMAND
The echo command is used to display messages on the screen. For example,
$ echo This is an example of the echo command<Enter>
This is an example of the echo command.
$
The echo command displays the enclosed text on the screen. It is preferable to
enclose the message to be echoed within double Quotes. By default, the echo command
displays the text and then puts a newline character at the end of the text. The newline
character causes the cursor to move to the next line after the text is displayed. This
default can be changed by using certain characters is the command.
For example,
$ echo This is an example of echo command /007 will display the text and
then sound the system bell.
Some of the characters used with echo are given below.

Character Function

\c Keeps the cursor on the same line of the screen after


displaying the argument
\n Displays an additional blank line after the argument.
\007 Displays the argument and then sounds the systems
bell on the next line.

Characters used with echo command.


READ COMMAND
The Bourne Shell script can read user input from standard input. The read
command will read one line from standard input and assign the line to one or more
variables. The following example shows how this works.

Example:
$cat read_script
echo Please enter a string of your choice
read a
echo $a
$
This simple script will read one line from standard input (keyboard) and assign it
to the variable a.
After executing the script the result is :
$read_script
Please enter a string of your choice
SURANA COLLEGE
SURANA COLLEGE
$
The line read from standard input can also be assigned to several variables as
shown in the following example/
Example :
$cat readexample
echo Please enter three strings
read a b c

echo $a $b $c
echo $c
echo $b
echo $a
$
After executing the script the result is:
Example :
$sh readexample
Please enter three strings
SURANA COLEGE
CENTRAL COLLEGE
MLA COLLEGE
MLA COLLEGE
CENTRAL COLLEGE
SURANA COLLEGE
$
EXAMPLE :
$cat read_ex
echo Enter line: \c
read line

echo the line was: $line


$
In this example, the \c option will suppress the carriage return. The single quote
marks protect the backslash from being interpreted by the shell. Also notice that the
double quote marks have no effect on the substitution of the variable line.
Example:
$read_ex
Enter line: Alls well that ends well
The line was: Alls well that ends well
READ-ONLY SHELL VARIABLES
The read-only shell variables are similar to the read-only user variable; except the
value of these variables is assigned by the shell, and the user CANNOT modify them
1 . Name of the Calling Program
The shell will store the name of the command you used to call a program in the
variable named $0.
It has the number zero because it appears before the first argument on the
command line.

Example :
$cat name_ex
echo The name of the command used
echo to execute this script was $0
$name_ex
The name of the command used
to execute this script was name_ex
$
2 . Positional Parameters
A Bourne Shell script can also read in command-line arguments. The first
argument is referred to as $1,the second is $2,and so on. Command-line arguments are
referred to as positional parameters.
The Bourne Shell will store the first nine command line arguments in the
variables named $1,$2,..,$9. These variables appear in this section because you cannot
change them using the equal sign. It is possible to modify them using the set command.
Lets look at an example Bourne Shell script to see how these are used.
Example:
$cat neat_shell
echo $1 $2 $3
echo $0 is the name of the shell script
echo There were $# arguments.
echo $*
$
Insure that the Bourne Shell script is executable by issuing this command:

Example:
$chmod a+x neat_shell
$
Now, if we type the name of the Bourne Shell scripts with no arguments, we get the
following results.
Example:
$neat_shell
neat_shell is thename of the shell script
There were 0 arguments.
$
in this sample session, there were no arguments given so none were printed. $0 is the
positional parameters that refers to the name of the script. Since there were no arguments
given with this invocation of neat_shell, there were zero arguments listed.
Example:
$ca arg_ex
echo The first five command line
echo arguments are $1 $2 $3 $4 $5
$arg_ex Rama Sita Lava
The first five command line
arguments are Rama Sita Lava
$
The script arg_ex will display the first five command-line arguments. The variables
representing $4 and $5 have a null value.
The Bourne Shell variable $* represents all of the command-line arguments as shown in
the following example.
Example:
$cat display_ali
echo $*
$display_all Rama Sita Lava
Rama Sita Lava
$
The Bourne Shell variable $# contains the number of argument son the command line.
This is a string variable that represents a decimal number. You can use the expr utility to
perform calculations with that number and test to perform logical tests on it.
Example:
$cat num_args
echo this script was called with
echo $# arguments
$num _args Rama Sita Lava Kusa
This script was called with 4 arguments
$

Shift
The shift command promotes each of the command line arguments. The second
argument, represented by $2, is now the file argument, represented by $1. The third
becomes the second and so on until the last arguments (as $1 through $9). The shift
command gives you access to the tenth, and the first becomes unavailable. There is no
unshift command that will return the arguments that are no longer available.
Example:
$cat demo_shift
echo arg1=$1 arg2=$2 arg3=$3
shift
echo arg1=$1 arg2=$2 arg3=$3
Shift
echo arg1=$1 arg2=$2 arg3=$3
shift
echo arg1=$1 arg2=$2 arg3=$3
shift
$demo_shift Rama Ravi Raju
arg1=Rama arg2=Ravi arg3=Raju
arg1=Ravi arg2=Raju arg3=
arg1=Raju arg2= arg3=
demo_shift:cannot shift
$
The Bourne Shell will display an error message when the script executes a shift command
after it has run out of variables.
Set
The set command will display a list of all the variables that are set when it has no
arguments.
Example:
$set
HOME=/user0/sri
IFS=
LOGNAME=Kanth
MAIL=/usr/mail/kanth
MAILCHECK=600
PATH=:bin:/usr/bin
PSI=$
PS2=>
SHELL=/bin/sh
term=vt100
TZ=MST7MDT
$

When set is called with arguments, it sets the value of the command line arguments ($1-
$n) top the arguments. The example sets the first three arguments.
Example:
$cat set_ex
set SURANA COLLEGE
echo $#: $*
$set_ex
3: SURANA COLLEGHE
$
expr
The expr command will perform arithmetic in the Bourne Shell.
command format expr expression
The arguments are taken as an expression. After the evaluation has taken place, the
result is written to standard output. The terms of the expression must be separated by
blanks. Special characters to the shell be escaped. Strings containing blanks or other
special characters must be quoted.

Example
$expr 7+8+10
25
$expr 10-8
2
$expr 10* 4
40
$expr 135/5
27
$
expr will also work with user defined variables as in the following
Example:
$cat data
8
15
25
$cat express
count=0
tot=0
for a in cat data
do
tot=expr $tot +$a
Count=expr $tot/$count+1
done
avg =expr $tot/$count
echo The average is $avg
$
Lets execute the script express with tracing on so we can follow the execution.
Example
$sh x express
count=0
tot=0
+cat data
+expr 0+8
tot=8
+expr 0 +1
count= 1
+expr 8 + 15
tot=23
+ expr 1 +1
count=2
+expr 23 +25
tot=48

+ expr 2 + 1
count=3
+expr 48 /3
avg=16
+echo The average is 16
The average is 16
$
COMMAND SUBSTITUTION
we can execute a command by enclosing it within two grave accent marks [these
are sometimes called back quotes ()]. The Bourne shell will replace the command and
the grave marks with the output from the command.
Example:
$cat dir
dir =pwd
echo you are using the $dir directory
$
Note: The grave marks lean to the left, and the apostrophes lean to the right. The grave
marks enclose the pwd command.

Example:
$dir
you are using the /user0/srik directory
$
The important thing to notice here is that the pwd command was executed ; and the
output,/user0/srik, was then assigned to the variable dir.
it is not necessary to assign the output of a command to a variable as shown in the
previous example. The command substitution can occur directly as shown in the next
example.
Example:
$cat dir2
echo you are using the pwd directory
$dir2
you are using the /user0 /srik directory
$
One final example will show a practical use of command substitution. This Bourne Shell
script will use the date command to provide the date in a useful format.
the normal output from the date command looks like the following.
Example:
$date
wed mar 19 18:02:05 MDT 2003
$

Heres a Bourne Shell script that rearranges the output into a more useable format.
Example:
$cat datesety
set date
echo $*
echo
echo Argument 1:$1
echo argument 2:$2
echo arguments3:$3
echo argument 4:$4
echo
echo $2 $3 $6
$dateset
Wed Sep 12 18 :02 :05 MDT 1990
argument 1: Wed
Argument 2:Sep
Argument 3: 12
Argument 4: 18:02 :05
Sep 12, 1990
$
The first command is the Bourne Shell script date set uses the grave accent marks to set
the command line argument variables to the output of the date command. The next
commands show the first four of these argument variables. The final command displays
the arguments in a different order that could be useful in a report or a later.
COMMENTS IN SHELL SCRIPTS
Comments can be inserted into the Shell script by beginning each
comment line with the pound symbol (#) or a colon (J. All characters after the comment
character will be ignored by the shell. The only exception to this rule is that the first
character of the first. Line must not be a pound symbol; if the first character is a pound
sign, the Bourne Shell tries to execute the script as if it was written in CShell syntax.
Example :
$cat com_sub
#The first line sets your present working directory
#to the variable directory
directory=pwd
#The second line sets the date to the variable when
when=date
: The third line will echo on the screen
echo You are in $directory on $when
: You could have said echo :

: You are in pwd on date


: to have a one line program
$
LOCAL AND GLOBAL SHELL VARIABLES
When a variable is referenced, it is known only to the shell that created it. If a
new shell is created by typing Sh, this new shell is born unaware of the parent shells
variables. Now the same variable name (as in the parent shell) can be given a different
value without the parent knowing about it. Such a variable is called a local variable.
The following examples illustrates the above concept.
$ college=Surana
$ echo $(college)
SURANA
$sh #Creates a new shell
$echo $(college) #there is no response.
$college=AIT
$echo (College)
AIT
$<press ctrl and d> #Returns to parent shell
$ echo $(College)

SURANA #Parent is unaware of AIT


$sh #Creates a child shell
$echo $(college) #value AIt is destroyed
$<press ctrl and d > #Returns to parent.
in many instances, it may be necessary for all the child shells to know about the
parent shell variables. The Bourne shell provides the export command to archive this.
Any shell variable given as an argument to this command will be passed on to all
subsequent child shells. Such a variable is called a global variable. This is illustration in
the following commands.
$college = SURANA
$export college
$echo $(college)
SURANA
$sh #creats a new child shell
$echo (college)
SURANA #child shell has the variable college
$
$college=AIT #gives new value to college
$echo $(college)
AIT
$<Press ctrl and d> #Returns to parent shell
$echo $(college)
SURANA #parents shell continues to have SURANA
$
The last two commands show that variables can be exported or passed on to child
shells, but the reverse is not true. This is because the expert command causes a copy of
the variable name and values to be passed onto a child shell, the value of the copy can be
changed by the child shell but when it dies, so does the copy. The original variable
remains untouched.
STANDARD FILES IN UNIX
Standard input File :
In UNIX, when a user executes a command, the shell runs the command and
assigns to it the keyboard as the source of input. The keyboard is referred to as the
standard input file.
Let us take an example of the cat command. When followed by a filename, all the
lines in the file are displayed till the end of file. Without the filename, however, the cat
command takes its input from the standard input files as shown below.
$cat<Enter>
The cat command waits for input from the keyboard. As a user enters characters
from the keyboard, they are displayed on the screen as shown below

$cat <Enter>
UNIX OPERATING SYSTEM<Enter>
UNIX OPERATING SYSTEM
Cursor waits at next line.
The user can keep on entering lines, to indicate the end of input, the user has to
press ctrl and d. the $ prompt then appears on the VDU.
Not all the commands use the standard input.
For example, cd command does not use the standard input file.
In UNIX, the standard files are always assigned a number called the file
descriptor, The file descriptor 0 is assigned to the standard input file.
Standard Output file
In UNIX, the shell assigns VDU as the destination for the Output of any
command that it executes. The VDU is referred to as the standard Output file.
Note : VDU visual display unit.
for example, when you issue the command
$ls <Enter>
The shell executes the command and sends its Output-directory listing to the
standard Output file, net all commands use the standard Output file for output. For
example, mkdir command does not use the standard Output file.
The file descriptor I is assigned to the standard Output file

Standard Error file


When an invalid command is typed at the $ prompt the shell displays appropriate
error messages on the VDU. The VDU is thus also the standard error file.
For example, the cat command followed by a filename which does not exist will
generate an error message on the VDU. The file descriptor 2 is assigned to the standard
error file.

Redirection
Redirection changes the assignments for the standard input , standard output and the
standard error. Using redirection, the input to a command can be taken from a file other
than the users terminal keyboard. Similarly, the output of a command or the error can be
written onto a disk file or onto the printer, instead of the VDU.

Following are the three types of redirection in UNIX.


Input redirection
Output redirection
Error redirection
Input redirection
The following example illustration the usage of input redirection.
$cat <test1 <enter>
Here , <(less than symbol) implies input redirection from the named file. The cat
command will take each line of the file test1 as input and display it on the VDU.
thus, in UNIX, it is possible to specify that the standard input, instead of coming from
the standard input file comes from a disk file. The above command can also be written
using the file descriptor as:
$cat 0<test1<enter>
here, 0 indicates input redirection.
Output Redirection
The following example illustrates the usage of output redirection.
$cat temp1> temp2<Enter>
here,> (greater than symbol) Implies redirection of output to the named file. The output
of the cat command is written onto a disk file called temp2.
In output redirection, the file to which the output is redirection is first created on disk as
an empty file and then the output is sent to this file. However, if the named file
(temp2) already exists, its contents will be deleted before the output is written to it. If the
user wants to append the output to temp2 file, the command to be given is
$cat test1 >>test2 <Enter>
The previous command can also be written using the file description as:
$cat test1 1 > test2 <Enter>
Here, 1 >indicates output redirection.
Error Redirection:
The following example illustrates the usage of error redirection.
$cat test 2 > error mesg <enter>
assume that the file test does not exist in the current directory. So, when a user tries to
execute this command, UNIX will generate an error message since the execution is
unsuccessful. This message, which would otherwise be displayed at the terminal VDU
(standard error file), will now be written onto the file called error-mesg. As in the case of
output redirection, error redirection also first creates the file to which the error message
are redirected and then writes the error output onto the file.
QUOTING AND REDIRECTION
Here we look at different means of quoting text in script and at a couple of input output
redirection facilities that are only relevant in scripts.
Strong () and weak () quotes
So far, we have used single quotation marks () around text that we echoed when we
wanted to preserve extra spaces between words. For example:

$ echo o o
o o
$
That does not always work though, as this example shows:
$echo o $variable o
o $variable o
$
The problem is that the shell does not substitute the value of parameters and variables
inside single quotation marks because they take away the special meaning of the dollar
sign. Fortunately, we can use double quotation marks () instead:
$variable =x
$echo o $variable o
o x o
$
Double quotation marks preserve the extra spaces but do hide variable or parameters.
if some dollar signs are to be quoted and some are not, we can use double quotes and
backslashes (/) together:
$echo \$ $variable \$
$ x $
$
Sometimes we have to mix both kinds of quotes as in :
$echo are stronger than
are stronger than
$
We could not use:
echo \\ are stronger than
Because single quotes even hide backslashes.
Redirection in scripts
In a script the individual commands may have their standard input or output redirected.
Any input or output that hasnt been redirection inside the script, is free to be redirected
when the script is called. This script is a modification of an earlier one:
$more newcmd
date
pwd
ls >file1
$
The output from li is tied to file1. the output from date and pwd is free. If we call the
script and redirect its output:
$newcmd >file2
$
Only the output from date and pwd will be written to file2.

Redirecting output to the same file


if we wish to send the output from two of the commands in our script to the same file,
we could do this:
$more newcmd
date
pwd >file1
ls >>file1
$
so that the second ( or later) commands append to the file. However, there is a tidier
method :
$ more newcmd
date
{ pwd
ls
} >file1
$
The braces ({ and }) are used to group commands together so are known as met
characters. Users should avoid using these characters in filenames as results might be
unpredictable. We have already seen several met characters, for example, vertical bar (),
or the greater than (>) or less than (<). The function of met characters can be different
depending on whether the shell or a UNIX tool interprets the character.
META CHARACTERS
Characters that have special meanings to the shell are known as met characters. Users
should avoid using these characters in filenames as results might be unpredictable . We
have already seen several met characters, for example, vertical bar ( ), or the greater than
(>) , or less than (<). The function of met characters can be different depending on
whether the shell or a UNIX tool interprets the character.

UNIX Char Function

& perform command in background


= assignment operator
; command separator
\ continuation of command line
\m literal translation of met character m
turn off special meaning
` process immediately
group characters into single argument
# comment follows
* wildcard filename substitution
? Wildcard filename substitution single character

UNIX Char Function

$$ process id
$? Exit status
$< read one line from standard input
. Current directory
[] selective filename substitution

Wildcards
The following table shows how UNIX expands wildcard definitions:

UNIX example meaning

* # All files the current directory and one level below


. # Files in the current directory
*.* # All files that contain a period in the filename
?.com # All files in the current directory that end In .Com
and have one character preceding the period
UNIX example meaning

name [xyz] # All files in the current directory namex ,


namey, or namez
name [a-z] # All files in the current directory namea
through namez
name [a-z4] # All files in the current directory, namea
through namez and name4

There are no absolute rules concerning the use wildcards. The output produced by
the wildcard expansion process is command dependent. For instance, the ls* command
will list file in the current directory and the files in the next lower level as well. The we *
(word count) command will produce output for the files in the current directory only.
Thus as you can see commands vary In how wildcards are expanded.

Simple shell programs

# program 1 : Write a shell script to find the length of a string


# vi length

clear
echo "**************** PROGRAM TO FIND THE LENGTH OF THE STRING
*****************"
echo
echo -n "Enter a String: "
read str
echo
echo
len=`echo $str | wc -c`
len=`expr $len - 1`
echo "Length of the string $str = $len"
# Program 2: Write a shell script to find no. of vowels in a string
# vi vowels

clear
echo "***************** PROGRAM TO FIND NO. OF VOWELS IN A STRING
***************"
echo
echo
echo -n "Enter a String: "
read str
len=`echo $str | wc -c`
len=`expr $len - 1`
count=0
i=1
while [ $i -le $len ]
do
ch=`echo $str | cut -c $i`
case $ch in
[ aeiouAEIOU ]) count=`expr $count + 1`
esac
i=`expr $i + 1`
done
echo
echo
echo "Number of vowels in string $str = $count"

# Program 3: Write a shell script to find all the prime nos. in a given range.
# vi prime.

clear
echo "************* PROGRAM TO FIND ALL THE PRIME NOS. IN A GIVEN
RANGE *****************"
echo
echo
echo "Enter the Range"
echo
echo
echo -n "Enter the lower limit: "
read m
echo -n "Enter the Upper limit: "
read n
echo
echo
if [ $m -le $n ]
then
echo "PRIME NOS. BETWEEN $m AND $n ARE: "
while [ $m -le $n ]
do
i=2
var=`expr $m / 2`
while [ $i -le $var ]
do
if [ `expr $m % i` = 0 ]
then
break
fi
i=`expr $i + 1`
done
if [ $i -gt $var ]
then
echo $m
fi
m=`expr $m + 1`
done
else
echo INCORRECT INPUT
fi

# Program 4: Write a Shell Script to find whether a given year is leap year.
# vi leap_year

clear
echo "************* PROGRAM TO CHECK FOR LEAP YEAR
******************"
echo
echo
y=$1
if [ "$y" = "" ]
then
y=`date + %Y`
fi
if [ `expr $y % 4` = 0]
then
echo "$y is a Leap Year"
else
echo "$y is not a leap year"
fi
# Program 5: Write a shell script to find whether given string is palindrome
# vi palindrome

clear
echo "**************** PROGRAM TO CHECK FOR PALINDROME STRING
**************"
echo
echo
echo -n "Enter the string: "
read str
len=`echo $str | ec -c`
len=`expr $len - 1`
i=1
while [ $i -lt $len ]
do
ch1=`echo $str | cut -c $len`
ch2=`echo $str | cut -c $i`
if [ $ch1 != $ch2 ]
then
echo "$str is not a PALINDROME STRING"
exit
fi
i=`expr $i + 1`
len=`expr $len - 1`
done
echo $str is a PALINDROME STRING

# Program 6: Write a shell script to find whether a no. is odd or even


# vi oddeven

clear
echo "************** PROGRAM TO CHECK AN ODD OR EVEN NUMBER
*************"
echo
echo
echo -n "Enter a number: "
read n
echo
echo
if [ `expr $n %2` = 0 ]
then
echo $n is an EVEN number
else
echo $n is an ODD number
fi
# Program 7: Write shell script to check current directory file permissions
# vi filepermission

clear
echo " PROGRAM TO CHECK FILE PERMISSIONS IN CURRENT DIRECTORY "
echo
echo
line=1
for files in *
do
tput cup $line 1
echo -n $files
if [ -f $files ]
then
tput cup $line 30
echo -n FILE
else
tput cup $line 30
echo -n DIRECTORY
fi
if [ -r $files ]
then
tput cup $line 45
echo -n READABLE
fi
if [ -w $files ]
then
tput cup $line 57
echo -n WRITEABLE
fi
if [ -x $files ]
then
tput cup $line 70
echo -n EXECUTABLE
fi
line=`expr $line + 1`
done
# Program 8: Write a shell script to fine the factorial of a number
# vi factorial

clear
echo " PROGRAM TO FIND FACTORIAL OF A NUMBER"
echo
echo
echo -n "Enter a number: "
read n
i=2
fact=1
while [ $i -le $n ]
do
fact=`expr $fact \* $i`
i=`expr $i + 1`
done
echo
echo
echo $no ! = $fact

# Program 9; Write a shell script to reverse a string


# vi reverse

clear
echo " PROGRAM TO REVERSE A STRING"
echo
echo
echo -n "Enter a string: "
read str
echo
echo
len=`echo $str | ec -c`
len=`expr $len - 1`
echo -n "REVERSE of $str is: "
while [ $len != 0 ]
do
ch= `echo $str | cut -c $len`
echo -n $ch
len=`expr $len - 1`
done
echo
ehco
# Program 10: Write a shell script to read & Print candidate detials
# vi candidate

if [ -f candidate ]
then
rm candidate
fi
a="Y"
while [ $a != n -o $a != N ]
do
clear
echo " PROGRAM TO READ CANDIDATE DETAILS"
echo
echo
echo "Enter Candidate Details"
echo
echo
echo -n "NUMBER: "
read no
echo -n "NAME: "
read name
echo -n "AGE: "
read age
echo -n "SEX: "
read sex
echo -e "$no\t$name\t$age\t$sex" >> candidate
echo
echo
echo -n "DO U WANT 2 CONTINUE [y/n] ? "
read a
done
echo -e "$no\t$name\t$age\t$sex" >> candidate
echo
echo
echo -n "DO U WANT 2 CONTINUE [y/n] ? "
read a
done
clear
echo " PROGRAM TO PRINT CANDIDATE DETAILS"
echo
echo
echo "CANDIDATE DETAILS ARE"
echo -e "Number \t Name \t Age \t Sex"
echo
cat candidate

También podría gustarte