PAGEFLOP
FORWARD
SELECTOR
SELAGAIN
WRONGSEL
YOUR SELECTION IS NOT IN THE 0 - #SELIMIT RANGE Please try again
AANVANG
Copyright CourseWare Technologies Inc., 1985-88
Lesson - 4
SHELL PROGRAMMING
MENU
Shell Programming|Topics to Learn|4-0|16,41
# Topic
--- -----
1 - Introduction
2 - Shell Procedures
3 - Shell Wild Cards
4 - Shell Variables
5 - User Variables
6 - Read-Only Variables
7 - Command Substitution
8 - Control Flow
9 - Command Grouping
10 - Setting up Your Programming Environment
11 - More Shell Scripts
12 - Lesson Review
0 - Return to the Main Menu
P1
Shell Programming|Introduction|4-1.1|10,54
The Shell is the UNIX system command processor.
It is a program which is a:
* command interpreter
* set of command procedures
* programming language
Programs and shell command procedures have the
same command syntax.
P2
Shell Programming|Introduction|4-1.2|12,54
This lesson is not an introductory discussion
of the UNIX Shell virtues. At this point you should
be familiar with I/O redirection, pipes and background
processing.
This lesson will serve as a guide for using:
* shell wild cards,
* shell variables,
* shell procedures or shell scripts, and
* a customized programming environment.
P3
Shell Programming|Introduction|4-1.3|4,54
If you are familiar with the Shell facilities,
you may skip this lesson; if you are not, then the
material in this lesson will be a major stepping stone
for better understanding of the subsequent lessons!
P4
Shell Programming|Shell Procedures|4-2.1|11,54
Normally when you execute several commands, you
would enter each one, followed by the new line character,
(<CR>), and wait for each command to finish before
entering the next one.
Instead of executing one command at a time, you
may enter a sequence of commands on the same line if
you separate the commands with the shell command delimiter,
a semicolon ( ; ). The command interpretation begins
after the new line character has been received.
P5
Shell Programming|Shell Procedures|4-2.2|7,54
As an alternative to using the ; , you can
put all of the commands into a file and have the
Shell read the file and execute each command in it.
A file containing a sequence of commands is
called a shell procedure or a shell script.
P6
Shell Programming|Shell Procedures|4-2.3|6,52
There are two ways to invoke a shell script:
* give the file execute permission and enter
the file name or
* use the sh or csh command with the file name
as an argument.
P7
Shell Programming|Shell Procedures|4-2.4|11,52
The syntax for invoking a shell script with
the Shell command is:
sh file [argument(s)] under the Bourne Shell
csh file [argument(s)] under the C Shell
If the file containing a shell script has execute
privilege, you may simply invoke the file without the
sh or csh prefix.
P8
Shell Programming|Shell Procedures|4-2.5|7,54
Whether you are using sh or csh, each interprets
what you type at your shell prompt. Provided your
input matches one of the Shell/UNIX commands, the Shell
will invoke that command, otherwise the Shell gives you
the message:
command_name: not found
P9
Shell Programming|Shell Wild Cards|4-3.1|9,54
Shell wild cards are characters that have a
predefined meaning to the Shell. They are used to
generate multiple file names.
When one of these characters appears on the
command line, the Shell will expand the argument into
a list of names that in some way match existing file
names (like the Joker can match any card in a poker game).
P10
Shell Programming|Shell Wild Cards|4-3.2|16,58
* matches any character or string of characters,
(including an empty string). For example, in the command:
ls -l *.c
the asterisk is used to match any file name that ends in
".c", so the command prints a detailed listing on all
files whose names end in ".c".
? matches any single character. For example,
lpr ?
will send any file with a single character name to the
off-line printer.
P11
Shell Programming|Shell Wild Cards|4-3.3|11,54
[ ... ] matches any single character that
appears in the brackets. For example,
nroff chapter[1234567] OR nroff chapter[1-7]
will nroff all files whose names begin with chapter
and end with a character from 1 to 7.
ls [A-Z]*
will list any file beginning with a capital letter.
P12
Shell Programming|Shell Wild Cards|4-3.4|13,54
Let's look at a few more examples using wild cards in
commands.
echo *des*
echoes or prints the names of all files containing the
string des.
cc prog[1-3].c
compiles three files: prog1.c, prog2.c, and prog3.c.
rm prog*[457]
removes files whose names begin with prog and end with
4, 5, or 7.
P13
Shell Programming|Shell Variables|4-4.1|16,54
A variable is an object which changes its value
during the life of a program, and the Shell is a program.
The Shell allows you to define variables and assign
values to them. There are three types of variables:
* Shell variables are declared and initialized by the
Shell, but you can read them and change them.
* Read-only variables are declared and initialized by
the Shell. You can read them but you cannot change them.
* User variables can be declared, initialized, read
or changed by you either on a command line or from a
shell script.
P14
Shell Programming|Shell Variables|4-4.2|12,54
Some variables have special meaning to the Shell.
Their names should be avoided for general use. They
include:
PATH specifies which directories the Shell is to
look in when it is searching for commands.
Directory names are separated by a colon (:).
MAIL is the pathname of the user's mail file.
HOME is the absolute pathname to user's home
directory. This is the default argument for
the cd command.
P15
Shell Programming|Shell Variables|4-4.3|13,54
CDPATH is the list of directories that are searched
by the cd command.
PS1 is the primary shell prompt string; the
default is $ under the Bourne Shell and %
under the C Shell.
PS2 is the secondary shell prompt used when further
input is needed. The default is > or ? .
All of these variables are typically set in the .profile
or .login file in your home directory.
P16
Shell Programming|Shell Variables|4-4.4|12,44
The default search path is:
/bin, /usr/bin
You can enter echo $PATH to see your
current path.
NOTE: You must precede a variable name
with a $ when you want to retrieve the value
of the variable.
P17
Shell Programming|Shell Variables|4-4.5|11,54
You can modify your search path by redefining
the PATH variable.
If you wish to have the Shell search for a requested
command first in the current directory (.), then in
your /bin directory, then in /usr/bin and finally
in /etc the new variable assignment command would
look like:
PATH=.:/bin:/usr/bin:/etc
P18
Shell Programming|Shell Variables|4-4.6|4,52
You can change the primary shell prompt string
to Yes? , for example, by entering:
PS1="Yes? "
TOPIC5
Shell Programming|User Variables|4-5.1|14,54
Because the Shell is a programming language, it
provides the user with the capability of defining
variables in addition to the built-in variables.
A variable name is made up of letters and digits,
but must begin with a letter or an underscore.
In a UNIX command line, the Shell interprets a
character string as a variable when the character
string is preceded by a $ , eg:
du $sys1 $sys2
P19
Shell Programming|User Variables|4-5.2| 18 , 52
A variable may be set by entering an assignment
command, e.g.,
$ var1=abc (Bourne Shell)
% set var1=abc (C Shell)
The echo command may be used to display the
values of certain variables. To display the
variables defined above:
% echo $var1
abc
If you forget to precede the variable name with a
dollar sign, as echo var1, you will get: var1.
P20
Shell Programming|Read-Only Variables|4-6.1|14,54
The shell has a set of special variables called
read-only variables. The names of these variables
begin with a $ . The Shell sets these variables
before executing a command except for $ ? which it
sets after executing each command. These special
variables are used often in Shell procedures in
diagnostic processing.
Let us look as some of these variables
$? - the exit status (return code) of the preceding
UNIX command. It is a decimal value.
$0 - the name of the command being executed.
P21
Shell Programming|Read-Only Variables|4-6.2|11,59
$# - the number of positional parameters (in decimal,
the - command is not counted).
$$ - the process number of the current shell (decimal value).
$! - the process number of the last process run in
the background.
$- - the current shell flags, such as -x which produces
an execution trace and -v which causes the lines of
the procedure to be printed as they are read.
P22
Shell Programming|Command Substitution|4-7.1|13,54
The standard output from a command can be
substituted in a way similar to assigning a value to
a variable.
For example, if user's current directory is
/usr/fred/doc, the command:
dir='pwd' is equivalent to dir=/usr/fred/doc
Thereafter, the value $dir may be used instead of
/usr/fred/doc.
P23
Shell Programming|Command Substitution|4-7.2|15,54
When a shell procedure is invoked, the Shell
implicitly creates positional parameters:
the name of the command itself is called $0 ,
the first argument is called $1 , and so on.
One can explicitly force values into these
positional parameters by using the set command, e.g.,
set red white blue
will assign red to the first positional parameter ($1),
white to $2, and blue to $3. In addition, it will
unset parameters $4, $5, etc. even if they were
originally set.
P24
Shell Programming|Control Flow|4-8.1|16,54
The shell is also a programming language with
power an order of magnitude higher than that of a
typical programming language.
Both the Bourne and the C Shells have control
constructs to alter the flow of control within a
shell script. They are:
Bourne Shell C Shell
-------------- ---------
if-then-else-fi if-else-endif
for foreach
while while
until case
case
P25
Shell Programming|Control Flow|4-8.2|8,54
The if control structure has the following syntax:
if this command is successful
then execute all the following
commands up to the next 'else'
else execute this set of
commands up to the next 'fi'
fi
P26
Shell Programming|Control Flow|4-8.3|16,54
TASK: Check for mail and print an appropriate message.
---- if-then-else statement example ----
1: if test -f $MAIL
2: then echo "You have mail."
3: else echo "No mail, sorry."
4: fi
----------------------------------------
EXPLANATION
1: tests to see if the file assigned to the $MAIL
variable exists. If it does,
2: then the string "You have mail" is printed on the
terminal.
3: If the mail file doesn't exist, the string "No mail,
sorry" is printed.
P27
Shell Programming|Control Flow|4-8.4|7,50
The for control structure has the following syntax:
for a variable in this list of values
do all of the following commands
until you encounter a
'done' statement
done
P28
Shell Programming|Control Flow|4-8.5|17,54
TASK: To make list of disk usage for users in the /usr2
directory.
--------- for statement example ----------
1: echo `date` > usage_usr2
2: for i in /usr2/*
3: do
4: du -s /usr2/$i >> usage_usr2
5: done
------------------------------------------
EXPLANATION
1: opens a file usage_usr2 and puts the date in it
2: says that the shell variable "i" will take on the
name of every file or subdirectory in the /usr2 directory.
4: will run the du -s command for each one and append
the disk usage results to the file usage_usr2.
P29
Shell Programming|Control Flow|4-8.6|7,54
The while control structure repeats while a certain
test returns a true value. It has the following syntax:
while this test is true
do all of these
commands until
the next 'done'
done
P30
Shell Programming|Control Flow|4-8.7|14,60
TASK: Create a program that checks every 5 seconds to see if
a specified file has been removed.
--------- while statement example -------
1: while test -r lockfile
2: do sleep 5
3: done
-----------------------------------------
EXPLANATION
1: tests to see if lockfile is readable; if it is,
2: program waits five seconds before testing again
3: when lockfile has been removed, the test fails and
the program ends
P31
Shell Programming|Control Flow|4-8.8|7,54
The until control structure repeats while a test
returns a false value. It has the following syntax:
until this is true
do all of these commands
until the next 'done'
done
P32
Shell Programming|Control Flow|4-8.9|14,54
TASK: Create a program that checks every 5 seconds to see if
a specified file has been created.
--------- until statement example -------
1: until test -r begin
2: do sleep 5
3: done
-----------------------------------------
EXPLANATION
1: tests to see if begin file is readable; if it is not,
2: program waits five seconds before testing again
3: when begin has been created, the test is passed and
the program ends
P33
Shell Programming|Control Flow|4-8.10|10,54
The case control structure has the following syntax:
case string in
string 1) if "string" is the same as "string1"
then execute all commands up to ;;
ignore the rest of the cases ;;
string 2) if "string" is the same as "string2"
then execute all commands up to ;;
ignore the rest of the cases ;;
esac
P34
Shell Programming|Control Flow|4-8.11|18,62
TASK: Write a program to request user input and echo
that input back to the user.
------------- case statement example --------------
1: echo -n "Enter a, b, or c: "
2: read letter
3: case $letter in
4: A) echo "You entered a";;
5: B) echo "You entered b";;
6: C) echo "You entered c";;
7: *) echo "You did not enter a, b, or c";;
8 esac
---------------------------------------------------
EXPLANATION
1: requests user input
2: reads input into a variable called letter
3: sets the test string to be the value represented by letter
4-6: if the test string has the value of A, B, or C, echo ...
7: the asterisk matches any other string of characters