You are on page 1of 574

e

e
eBook Collection
Linux Shell Script Entire Ebook
This is a Protected PDF document. Please enter your user name
and password to unlock the text.
Remember my user name and password.
If you are experiencing problems unlocking this document or you have questions
regarding Protectedpdf files please contact a Technical Support representative:
In the United States: 1-877-832-4867
In Canada: 1-800-859-3682
Outside the U.S. and Canada: 1-602-387-2222
Email: technicalsupport@apollogrp.edu.
1000-0001-54B2-0005B8F5
1
',%48)6

-2863(9'8-32 83 8,)
34)6%8-2+ 7=78)1
)2:-6321)28
-RXLMWGLETXIV]SY[MPP
9RHIVWXERHSTIVEXMRKW]WXIQW
(IJMRIXLI9RM\ERH0MRY\STIVEXMRKW]WXIQW
9RHIVWXERHGPEWWMJMGEXMSRWSJWSJX[EVI
9RHIVWXERHHEXE
9RHIVWXERHXLIYWIVVSPIW
9RHIVWXERHFEWMG0MRY\GSQQERHW
'VIEXIWLIPPWGVMTXW
8
he operating system is a set ot sottvare instructions that run the com-
puter. When you vrite shell scr ipt programs, you combine Iinux
operating system commands and programming logic to create automated
tasks. In this chapter, you vill learn about the major operating systems as
vell as teatures specitic to the Iinux operating system. You vill learn
about the types ot users in a Iinux environment, vhich vill help you
determine the type ot access and type ot scripts individuals need. Some
ot the common basic Iinux commands vill be discussed. You can use
these commands in scripts to make a user`s job easier. linally, to get you
started vith shell programming, you vill create a tev shell scripts.
9NDRS1ANDING 3PRA1ING 7YS1MS
Softvare is a set ot instructions that are processed by the computer system. 1he
operating systen is sottvare that governs computer systems. 1he components in a
computer system are the users, the applications, and the hardvare. 1he operating sys-
tem acts as a liaison betveen these components. It is the operating system that allovs
you to save a tile to disk, retrieve a tile trom disk, run a spreadsheet application, print
a tile, compile a program, point and click vith your mouse, enter text commands, or
navigate the graphical user intertace (GLI,.1hink ot the operating system as the sott-
vare brains ot the computer system. ligure 1-1 highlights the relationship betveen
the operating system and the other components in a computer system.
1he Lerms "soLware" and "prorams" are synonymous in Lhe compuLer
indusLry.
8MT
Hardware Components
OperaLin sysLem
Disk drives Keyboard NoniLor Nouse PrinLer Processor RAN
(memory)
Users ApplicaLions
fIgure 1-1 Role o Lhe operaLin sysLem
2 Chapter 1 IntroductIon to the OperatIng System nvIronment
UnderstandIng OperatIng Systems 3
1here are many ditterent operating systems running many ditterent computer systems both
tor business and home use. Operating systems run large maintrame computers, server-
based netvorks, PC (personal computer, systems, laptops, and even small handheld devices.
Mainfrane operating systens are designed to handle the inputoutput (IO,, pro-
cessing, and storage requirements tor many users.1hese operating systems run maintrame
computers and are generally used in large corporations. An example ot a maintrame
operating system is the IBM Multiple Virtual Storage (MVS, system.
Netvork operating systens allov computers to share resources over a netvork. A
resource is a hardvare device, a sottvare program, or a tile. A printer that can be used by
multiple users is an example ot a shared resource. In the past a netvork vas detined as a
group ot computers and printers connected by cables. Hovever, vith the advent ot never
technology, computers and printers can communicate via vireless transmission as vell.
Netvork operating systems use protocol softvare to tacilitate the communication
among computers throughout a netvork. 1CPIP is the most common protocol used
today. 1ransnission Control Protocol/Internet Protocol (1CP/IP) allovs you to
connect to the Internet and brovse Web sites, pertorm searches, or shop online. Lach com-
puter, called a host, must have an IP (Internet Protocol) address to communicate vith
other computers on the netvork. 1he host may also have a Donain Nane Service
(DNS) nane such as Pedhat.com.1his is sometimes called its triendly name.1he DNS
name is used so people von`t have to remember the IP address ot a host.
In a netvork, servers are computers that allov other computers to connect to the server`s
shared resources. Clients are the computers that use the resources made available by the
servers. 1he client/server model is vhen a server computer handles the requests made
by the client computer.1here are usually more clients than servers in a netvork. Because
the server has to handle numerous client requests, the server typically has more memory,
hard drive space, and processing capability than the clients. Lxamples ot operating systems
that run on servers are Novell NetWare, Microsott Windovs N1 Server, 2000 Server, and
LNIXIinux. Windovs 93, Windovs 98, Windovs N1 Workstation, Windovs 2000
Protessional, and Windovs XP are examples ot client operating systems.You can also run
LNIXIinux as a client. Servers and clients must use the same protocol in order to com-
municate vith one another. Lven it clients are using ditterent operating systems, the use
ot a common protocol allovs communication to occur. In ligure 1-2, you can see the
server and clients in a netvork environment.
1
(fINING 1H 9NIX AND 0INUX 3PRA1ING 7YS1MS
1he LNIX operating system goes back to the 1960s. Several employees vorking tor
A181 developed an operating system based on the C language and called it LNIX.1he
initial version vas called A181 System Pelease V.1he operating system code vas treely
distributed to major universities vhere changes vere made to it. So, unlike proprietary
operating systems such as Microsott Windovs, Novell, and IBM, a single vendor has not
developed LNIX. 1here have been numerous versions ot the initial operating system,
and many vendors have customized LNIX to tit their ovn plattorms. IBM has vritten
a version ot LNIX called Advanced Interactive Lxecutive (AIX,, Sun has vritten Solaris,
and Hevlett-Packard has vritten HP-LX, and there are many others. Pecently, sott-
vare vendors vho have traditionally developed their ovn operating systems tor their
ovn hardvare are beginning to use the Iinux operating system.
1he Iinux operating system vas developed trom another version ot LNIX called MINIX.
It comes vith many built-in teatures, a tull compliment ot programming languages, com-
pilers, and system administration tools, and is available at a very reasonable cost.1able 1-1
shovs a listing ot some ot the versions ot the Iinux operating system and the associated
Web sites tor researching them. 1his book tocuses on the Iinux operating system.
ClienL compuLer ClienL compuLer ClienL compuLer
Server compuLer
fIgure 1-2 ClienL/server model in a neLwork
4 Chapter 1 IntroductIon to the OperatIng System nvIronment
DefInIng the UnIx and LInux OperatIng Systems 5
Iet`s look at some ot the teatures the Iinux operating systems otters.1hey are as tollovs
Multiuser capability
Portability
Multitasking
Ability to use multiple processors
Multiple modes ot operation
MultIuser CapabIlIty
A nultiuser operating system is one capable ot handling multiple requests by a variety
ot users. Many companies run Iinux as their mainstay operating system tor their busi-
ness because it provides a multiple user plattorm. 1hey can install their applications on
a Iinux server and have client computers access the application on the server over the
netvork. Some operating systems are single-user plattorms (only one user can use the
computer,, such as Windovs 93 and 98.
A plaLorm comprises boLh Lhe hardware and soLware combinaLion on which a
iven sysLem runs. For example, i Linux version 8.0 is Lhe soLware runnin on
an lnLel-based hardware sysLem, Lhen Lhe Lwo combined are called Lhe plaLorm.
PortabIlIty
Portability allovs you to carry the Iinux operating system to another hardvare system,
recompile it, and run the operating system. Ot course, this is alvays easier said than done
because installing an operating system can be an arduous task. Many operating systems
are vritten tor a specitic processor. Lach processor has its ovn instruction set, vhich
is the set ot instructions the processor uses to operate. 1he instruction sets ot ditterent
processors are typically not compatible.You can think ot an instruction set as being the
language specitic to the processor.
8MT
VersIon Web SIte
Debian www.debian.or
OpenLinux www.calderasysLems.com
SuSe www.suse.com
Slackware www.slackware.com
Nandrake www.mandrake.com
Red HaL www.redhaL.com
1able 1-1 Versions o Linux and Lheir Web siLes
1
1here are tvo general types ot processors.A conple instruction set conputer (CISC)
has a large set ot instructions in its instruction set. A reduced instruction set conputer
(RISC) has a reduced number ot instructions in its instruction set but relies on hardvare
to pertorm the tasks not provided by the instruction set. Because ot the enhanced hard-
vare, a PISC processor is taster, yet more expensive, than a CISC processor.1he processor
in most PCs is a CISC processor. Windovs 98 runs only on CISC-based Intel processors.
Ped Hat Iinux can run on both CISC and PISC processors.1he portability ot the Iinux
operating system gives you more hardvare options on vhich to run the operating system
because you can choose to run Iinux on either type ot processor.
MultItaskIng
Multitasking is vhen the operating system can handle multiple jobs at seemingly the same
time. When a program executes, it is knovn as a job or process. 1echnically, the operating
system pertorms only one job at a time. Hovever, through time slicing, the operating sys-
tem gives each job a little bit ot time.1he jobs take turns being processed in a round-robin
manner. Iet`s look at an example. Assume the operating system gives each job only one
minute ot CPL time. It a job exceeds the one-minute time slice, it is sent to the svap tile.
1hen the next job in line begins processing. It this job tinishes in less than a minute, then
the system can retrieve the next job in the process queue or continue processing the tirst
job that vas sent to the svap tile. 1his is done tor all jobs until there is no more vork to
be done. 1he advantage ot this is that one large job lasting 13 minutes or so von`t slov
dovn the vhole system and keep smaller jobs that require less processing time trom being
completed.
1he Iinux operating system employs preemptive multitasking as opposed to cooperative
multitasking.With preenptive nultitasking, the operating system has the ability to take
control ot the system trom an application. With cooperative nultitasking, the applica-
tion takes control ot the system resources.1he advantage ot preemptive multitasking is that
it an application tails, the vhole system von`t necessarily crash. In cooperative operating
systems, a tailed application can cause the vhole computer to treeze or crash.
AbIlIty to Use MultIple Processors
1he ability to have several processors to improve overall throughput, or the amount ot
vork that can be put through the system, is another advantage ot the Iinux operating sys-
tem, and Iinux can accommodate up to 32 processors. Iinux also uses nultithreading
vhich allovs tor a program to be split across several processors, vith each processor vork-
ing on a ditterent piece ot the program at the same time.
6 Chapter 1 IntroductIon to the OperatIng System nvIronment
DefInIng the UnIx and LInux OperatIng Systems 7
Synnetrical nultiprocessing (SMP) tacilitates multithreading. SMP greatly enhances
throughput because several processors handle one large task instead ot a single processor
handling the same task alone. SMP is typical on systems vith a large number ot users vhere
throughput demands are great.
MultIple Modes of OperatIon
1he Iinux operating system operates in tvo modes. 1hey are as tollovs
Graphical user intertace (GLI,
1ext
GraphIcal User Interface (GUI) Mode
1he GLI program, called X Windovs, otters a Windovs look and teel to the Iinux envi-
ronment.What you see on your screen is called the desktop because it includes the tools
you need to pertorm daily tunctions. Some ot the tools provided as part ot the desktop
are a GLI tile manager, a Desktop manager and an Internet Web brovser. ligure 1-3
shovs a screenshot ot the Iinux Gnome desktop.
Linux also ives you access Lo Lhe lnLerneL by uLilizin Lhe necessary hardware
Lo run NeLscape CommunicaLor, Web browser soLware, and 1CP/lP.
8MT
fIgure 1-3 1he Linux Gnome deskLop
Opens Lhe Gnome menu
Web browser
1
ligure 1-4 shovs a screen shot ot the Iinux tile manager open on the desktop.
1ext Mode
Iinux also provides you vith a text mode intertace. In this intertace you use commands
to navigate the Iinux system and vrite your shell scripts. You vill need to use text or
graphical editors to vrite shell script programs. ligure 1-3 shovs a screenshot ot the
Iinux text mode open on the desktop ot the GLI.
fIgure 1-5 Linux LexL mode
fIgure 1-4 Linux ile manaer
8 Chapter 1 IntroductIon to the OperatIng System nvIronment
UnderstandIng ClassIfIcatIons of Software 9
You access the text mode in the Iinux operating system via a shell. Acting as an inter-
preter, the shell accepts commands trom the keyboard and either executes the command
or displays an error it the command encounters a problem.1echnically, the shell is a lan-
guage, so you must adhere to its syntax, or rules. A tev ot the shells available on Iinux
are listed in 1able 1-2.
9NDRS1ANDING 'LASSIfICA1IONS Of 7Of1WAR
It is alvays a good idea to knov vhat sottvare is running on your system.1his vay, you
are better equipped to troubleshoot in case a problem occurs. Also, sottvare can be under
a sottvare contract, so you may be able to contact someone it problems arise.
Sottvare is divided into the tolloving categories
System sottvare
Application sottvare
System Software
System sottvare includes the core components ot the system that must be present in
order tor the computer to operate. Lxamples ot system sottvare are
1he kernel
ob management sottvare
Memory management sottvare
Programming languages
Device drivers
Sottvare utilities
Shell Name DescrIptIon
sh 1he oriinal shell wriLLen by SLeven 8ourne, also known as Lhe 8ourne Shell
bash Publicly licensed 8ourne-Aain Shell compaLible wiLh Lhe oriinal 8ourne Shell;
Lhis is Lhe deaulL shell you eL aL loin
csh C-shell which uses a C-like synLax
ksh Publicly licensed Korn shell wriLLen by David Korn
1able 1-2 Various shell inLerpreLers available on Linux
1
1he kernel
1he kernel is the heart ot the operating system.When any computer system boots, a set
ot program instructions are loaded trom the hard drive and kept in memory. Many pro-
grams are kept, or cached, in memory tor speedy access, but the kernel is the core ot any
operating system that occupies memory as long as the computer remains on. It controls
all other sottvare activity. Only the most important and videly used programs are part ot
the kernel.1he kernel calls upon other programs that are held on disk or in other areas ot
memory by intertacing vith other operating system programs vith the hardvare ot the
computer system. Most operating systems have a kernel that remains in memory. Lxamples
include Iinux, Novell NetWare,Windovs N1, Windovs 2000, and Windovs XP.
1he kernel is cached in memory. Cachin means Lo keep prorams in mem-
ory or quick access. 8ecause memory access is asLer Lhan reLrievin iles rom
a hard disk or neLwork, cached prorams are reLrieved quicker.
Customizing your Iinux kernel allovs you to give your computer system ditterent capa-
bilities.You can modity your kernel by adding or removing support ot ditterent teatures
such as the ones shovn in ligure 1-6.
Job Management
It is the tunction ot the operating system to manage processes that are executing. In gen-
eral, vhen a program executes it is knovn as a job or process.
A daemon is a job LhaL runs in Lhe backround waiLin or work. Nany o Lhe
sysLem prorams are jobs run as daemons.
8MT
fIgure 1-6 Kernel eaLures you can cusLomize
8MT
10 Chapter 1 IntroductIon to the OperatIng System nvIronment
UnderstandIng ClassIfIcatIons of Software 11
Prior to job execution, a job is placed in a job process queue. A job process queue is
a holding area tor the job vhile it vaits its turn tor execution. A running process has
CPL and memory resources bound to it. 1he Iinux operating system uses a process
tree to keep track ot the processes on the system. When a program or command exe-
cutes, it is assigned a number, called the process ID (PID). 1he PID is used tor inter-
nal purposes by the operating system. 1he operating system uses the PID vhen
communicating vith the process. 1he process name is much like your ovn name and
the PID is much like your Social Security number.
Lach process is created trom a parent. Iinux uses the term spavning to describe one
process starting trom another. At times, a process may encounter problems causing it to
consume excessive CPL time or to become orphaned. lor instance, it process A spavns
process B, then process A encounters a problem and is killed and removed trom the
process tree, process B, vhich is still running, is said to have been orphaned.
Memory Management
Memory management sottvare allovs you to manage all ot memoryincluding both
physical memory and virtual memory. Virtual nenory is the concept ot the system
utilizing physical memory as vell as a section ot hard disk space tor accommodating
multiple processes. 1he use ot virtual memory tacilitates the multiuser and multitasking
teatures and capabilities ot an operating system.
1he area on Lhe hard disk reserved or virLual memory is someLimes called Lhe
pae ile or swap ile. 1he swap ile is creaLed durin Lhe insLallaLion o Lhe
operaLin sysLem.
Here is hov virtual memory vorks. Programs are loaded into physical memory, also
knovn as randon access nenory (RAM). Programs are allocated a certain amount
ot time, called a time slice.When memory utilization reaches a certain threshold or vhen
a process`s time is up, the system sends the program and its data to the hard drive. Here
the program is in a vait state and is placed temporarily on hold. When the system is
ready to process the program and data that is currently on hold, the program`s data is
sent back to physical memory tor main processing.
Maintrame operating systems and some netvork operating systems, such as Novell
NetWare, LNIX, Iinux, and Windovs plattorms, utilize virtual memory. One vay to
speed up your computer system is to add more memory to it. Another vay is to increase
the size ot your svap tile by allocating more disk space to it.
8MT
1
ProgrammIng Languages
Sottvare programs are vritten in languages such as C, C, ava, Visual BASIC,
COBOI, lOP1PAN or Assembly. Ianguages are divided into tvo major classitications
High-level
Iov-level
HIgh-level ProgrammIng Languages High-level programming languages are designed
vith people in mind. 1hey tend to be similar to Lnglish in style and are much easier tor
the programmer to read and comprehend than lov-level programming languages. lor
example, reviev the tolloving excerpt ot a COBOI programming language statement
IF HOURS > 40 THEN
PERFORM CALCULATE~OVER~TIME
ELSE
PERFORM CALCULATE~REGULAR~TIME
END~IF
In the example, it the hours exceed 40, then overtime is calculated. It the hours are
under and including 40, then regular time is calculated. You can clearly see hov this
sample COBOI program is very much like Lnglish. Lxamples ot high-level program-
ming languages include Perl, COBOI, C, BASIC, Visual BASIC, and lOP1PAN.
High-level programming languages must be converted trom their human-readable
torm into computer- or machine-readable torm.1his conversion can be done through
either compiling or interpreting. 1he compiler or interpreter is sottvare that is vrit-
ten to pertorm the conversion.
With conpiling, the entire program is converted into an executable program. Once it
is tree ot errors and compiled, the program is capable ot being run or executed. On many
systems, it is just a matter ot clicking an icon representing the program. Lxamples ot
compiled languages are C, C, COBOI, and lOP1PAN.
In the case ot interpreting, each line is converted into machine-readable torm as it is
executed. 1he statements vithin the program are still converted into machine-readable
torm, it`s just done line by line. 1hink ot an interpretive language as being one vhere a
minicompile is done tor each statement. Some examples ot interpretive languages are
Visual BASIC (hovever you can compile the code,, Perl, BASIC, and shell programs.
Low-level ProgrammIng Languages Lach processor has its ovn programming
language, otten called a lov-level programming language. 1he term lov-level is
used because the language is native to the processor instead ot being similar to
Lnglish. Lxamples ot these are the Assembly language statements that are specitic to
every computer system. So, you could not take an Assembly language program and
12 Chapter 1 IntroductIon to the OperatIng System nvIronment
UnderstandIng ClassIfIcatIons of Software 13
run it on just any system. Hovever, you are more likely to take a high-level program
and run it on another system vith maybe only a tev moditications. 1ake a look at
the tolloving excerpt trom an Assembly language program
L l,X
A l,Y
A l,Z
ST l,T
1he above programming code simply adds up a set ot three variables, X,Y, and Z, and
stores them in a variable named 1. It is not like Lnglish, and it greatly ditters trom the
COBOI program example you sav earlier.
DevIce DrIvers
Keep in mind that it you have a piece ot hardvare, such as a printer or scanner, you must
have sottvare that governs it. Device drivers are sottvare instructions that manage a
particular device. You must contigure the correct driver tor the type ot hardvare you
install. Lntortunately, it`s not uncommon to install a device driver incorrectly. 1ake a
printer driver tor example. A possible symptom ot an incorrectly installed printer driver
is that the printer`s output is garbled and unreadable. Another symptom is the printer
prints one line on a page and then advances to the next page to print the next line.
Remember, you musL use Lhe device driver LhaL oes wiLh Lhe device. ln oLher
words, i you are usin a brand X, model Y device, you musL use a brand X,
model Y device driver or Lhe device will noL uncLion properly.
Software UtIlItIes
Softvare utilities are commands that help augment the tunctionality ot the operating
system. 1hey are especially important because they can be used in combination vith
shell script programming logic to automate certain tasks.
1he tolloving are some sottvare utilities
Backup and restore
Compression and uncompression
Printer management
ackup and Restore One ot the most important aspects ot any job is backing up your
data.Whether you back it up to a tloppy disk, CD, hard drive, or tape, you should alvays
back up your data. Although many organizations use redundant servers in case one goes
dovn, or they use redundant disks storage, they still require their personnel to pertorm
backups.
8MT
1
Backups typically occur during ott-hours vhen users are not vorking vith application
tiles. 1he reason being that it you back up tiles during business hours, you cannot guar-
antee the backup has indeed backed up the data that is being processed at that moment
by the application. Also, some backup utilities do not backup tiles that are in use.
1he restore process is the copying ot the data that vas backed up to either its original
storage location or another one. 1he backup and restore processes should be tested to
verity they vork in case a real emergency ever occurs.
CompressIon and UncompressIon Most every tile has something in it that is
repeated. lor example, one ot the most common vords is the vord the, vhich occurs
in many documents and books, such as this one. Conpression is the process ot remov-
ing those repeating portions ot a tile, thereby making a nev smaller tile. Compression
varies based on the amount ot data that is duplicated and the compression algorithm that
is used.At times, compression can yield betveen a 73 and 90 savings.You vould gen-
erally compress a tile that is to be dovnloaded over the Internet. It takes less time to
dovnload a compressed tile because it is smaller. Another advantage ot compression is
that it saves disk space because ot the reduced tile size. Hovever, in order to utilize the
tile, you must uncompress it tirst.
PrInter Management 1he Iinux printing system uses the concept ot print queues to
temporarily hold print jobs. When a user sends a print job to a printer, the print job is
spooled to a directory tor the printer vhere it vaits.
1he Lerm "spool" is an acronym LhaL comes rom l8N mainrame Lerminoloy.
lL sLands or SimulLaneous Peripheral OperaLions OnLine.
Simply stated, it means the system can send a print job to the printer sottvare concur-
rent vith other system activities. It the printer is busy or not turned on, the print job
vaits in the print queue until the printer is ready to accept the request.When the printer
is ready to print, the print management sottvare looks in the printer`s directory, or
queue, and prints the next job. It then deletes the print job request trom the print queue.
ApplIcatIon Software
Application softvare is sottvare that assists users in pertorming typical ottice vork
such as vriting letters and business proposals, managing numeric intormation, and orga-
nizing large amounts ot data. As such, application sottvare is generally divided into these
major categories
Word processing
Spreadsheet
Database
8MT
14 Chapter 1 IntroductIon to the OperatIng System nvIronment
UnderstandIng ClassIfIcatIons of Software 15
Word-ProcessIng Software
Word-processing sottvare has been around since the early 1980s. Word-processing sott-
vare allovs you to create, modity, delete, save, and print ottice-quality documents. Word-
processing sottvare also includes the enhanced capabilities ot spell checker, dictionary, and
a thesaurus.1oday, Microsott makes Word and Sun Microsystems otters a vord-processing
package as part ot the Star Ottice sottvare package suite. Star Ottice runs on the Iinux
operating system.
Spreadsheet Software
Also during the early 1980s, a group ot students taking an accounting class grev tired
ot making numerous changes to the accounting sheets vhen only one number changed.
1hese students eventually started the Iotus Corporation, one ot the tirst companies to
create spreadsheet sottvare tor PCs. Spreadsheet programs allov you to manage numeric
data on a large scale. Spreadsheets hold data in cells, vhich are much like storage loca-
tions.When one cell changes, all cells reterencing the original cell also change. Cells are
labeled consecutively starting vith A1 and continuing as tar as your data demands.
Ietters represent the columns and numbers represent the rovs.
Spreadsheet programs are extremely povertul and can include programming logic.1hey
also include built-in tunctions. Functions are miniprograms that do the vork vhen you
supply the data, such as pertorming a mathematical calculation.
You will learn how Lo use shell scripL prorams Lo creaLe uncLions in ChapLer 8.
In this spreadsheet example, =AVERAGE{Al:A20| you can see the pover ot a spreadsheet
tunction.1he AVERAGE tunction is given, or passed, tvo valuesthe beginning cell in a cell
range,A1, and the ending cell in a cell range, A20.Whatever values are held in any ot the 20
cells in column A are included in the average. It a value in any cell in the range changes, the
average changes too.
Database Software
Database programs allov you to manipulate and manage data, create tables ot data tor orga-
nization, and join or combine data trom multiple tables to create vievs or subsets ot tables.
Data held in databases can be accessed quickly via a unique identitier called a key tield.
Ashton-1ate Corporation developed one ot the tirst database programs on the market tor
PCs in the 1980s called dBASL. Other companies such as IBM, Microsott, Oracle, and Sun
Microsystems have also developed database sottvare. Iinux comes vith a database prod-
uct called MySQI. It allovs you to add, delete, and modity data vithin databases.
8MT
1
9NDRS1ANDING (A1A
In order to successtully vrite shell script programs, you must understand vhat data is as
vell as the structure ot data. Data is made up ot rav tacts that are not much use until
they are processed into intormation. Consider the number 73. 1his is considered data.
You cannot look at the number 73 and tell it it is an exam grade, the outdoor temper-
ature, or someone`s age. Only vhen a program, in conjunction vith the computer`s
processor, processes the number can it become intormation. 1he programmer`s job is to
vrite program code to turn data into usetul intormation. 1hink ot data as a hierarchy
or a pyramid. ligure 1-7 shovs the data pyramid.
At the lovest level ot the data hierarchy are bits.1he term bit stands tor binary digit and
is either a zero (0, or a one (1,. Lach computer system has a character set that maps all
the letters on the keyboard to its appropriate bit sequence. American Standard Code tor
Intormation Interchange (ASCII, is a character set common among most computer
environments including all Windovs operating systems and the Iinux operating system.
Although you don`t typically use anything as small as a bit in your daily dealings vith
computers, you do need to understand the concept.
In the computer industry, the term byte reters to eight bits taken in sequence. Another
synonym tor the term byte is alphanumeric character. An alphanumeric character is
detined as any ot the letters A through Z, numbers 0 through 9, and special symbols.
Although it is up one notch on the data hierarchy, a character is generally the lovest
level ot the data hierarchy that people process.
Records:
1asha Liu, 400 Yona Dr., 8eijin, China
Fred SmiLh, 201 Apple Lane, ALlanLa, GA, 30033
Fields: 1asha Liu, Lires
8yLes: A 8 7 9 ; > z
8iLs: 0 0 1 1 0 0 1 0
Files:
Payroll.daL
lnvenLory.daL
fIgure 1-7 DaLa pyramid
16 Chapter 1 IntroductIon to the OperatIng System nvIronment
UnderstandIng Data 17
A group ot bytes is called a field. lor example, it you`ve ever tilled out a job or college
admission application, or even your 1040 tax torms, you knov that you must till in little
boxes or blank lines vith your personal data. Lach ot the boxes or blank lines is entered
into an application screen to be processed by a program. 1hese boxes and blank lines are
considered tields. lields are labeled, or given names, so that you may reter to the data con-
tained vithin them. lor instance, a tield called NAML, may have the tolloving data1asha
Iui. It you vanted to print the NAML tield, it vould print the name 1asha Iui. Notice
also that a tield is comprised ot characters or bytes.
A group ot related tields makes up a record. lor example, consider the employee records
containing the tield names and data shovn in 1able 1-3. 1here are three records vith six
tields each. In this case, you can think ot a record as a rov and think ot a tield as a column.
In most application systems, there is one unique identitying tield in a record called the
prinary key field. 1his tield is used to access the remaining tields in the records. 1he
purpose ot the primary key is to locate the data in the record etticiently. When a bank
teller asks you tor your bank account number, the account number is used as the pri-
mary key.Your Social Security number is used as a primary key vhen you till out your
tax returns or an employment application.
1o help you understand the primary key concept, think about hov the index in the back
ot this book vorks. It you vant to look up a term, you go to the index and look through
the alphabetical listing until you locate the page number reterence tor the term. 1hen,
you go to the actual page number that describes the term.1he primary key is analogous
to the term you seek in the index. In an application, the primary key tield is used to
locate the record containing the rest ot the data.
A grouping ot related records is called a file. A tile has a name and location tor vhere
the data is housed. A tile can contain tvo major types ot data, executable, or binary data,
and nonexecutable data.
Lecutable or binary files are tiles that have been compiled and pertorm some type
ot operation or task. 1hey are vritten using text editors tolloving the strict syntax ot
the language and then they are compiled.1he compilation process creates the executable
code. 1he commands that you`ll use in this book are executable tiles.
Name Address CIty State ZIp Phone
Sarah 1oar 214 ScoLL Way Concord NH 03301 555-5550
Xin Chun Liu 428 Aubrey Way Lilburn GA 30047 555-5551
Nolly Obakin 1027 Nichelle Lane 1ulsa OK 74101 555-5557
1able 1-3 Sample employee records
1
Noneecutable files are generally data that the executable tiles operate on.1he user runs
an application or program that creates data tiles. Data tiles can also be created automatically
by programs that run vithout user intervention. Lxamples ot nonexecutable tiles are text
tiles, vord-processing document tiles, spreadsheet tiles, database tiles, or picture tiles.
9NDRS1ANDING 9SR 6OLS
In the Iinux computing environment, there are several types ot users, each vith dit-
tering roles. Lnderstanding the role ot a user is important because it helps you decide
the type ot shell scripts that person might need on the job. Additionally, the role gov-
erns the type ot access the user has to the system. Here is a list ot the typical user types
Standard user
System Administrator or root user
Shell programmer
Standard Users
1he standard user, sometimes just called user, is the person vho uses the Iinux oper-
ating system on a daily basis. Lsers may also have access to commands via the text mode
and other programs in the GLI. 1hey also use the system to access applications. 1he
applications they need depend upon their tunctions in the organization. Consider this
example ot typical users` needs. An accounting manager may need access to the account-
ing application, an engineer may need access to a computer aided designcomputer
aided manutacturing (CADCAM, program, an insurance agent may need access to the
insurance adjustment application, and a travel agent may need access to the travel book-
ing application.
Lsers access the Iinux system by logging in using a user account. Generally, a computer
specialist, such as a System Administrator vho has authority to create the accounts, gen-
erates the user accounts. 1he user account should also have a passvord that is assigned
to it. Once the users log in, they usually set their ovn passvords.
System AdmInIstrator
1he Systen Adninistrator is a computer specialist vho is responsible tor the operations
ot the computer systems and netvork. Depending upon the size ot the operation, there may
be more than one System Administrator in an organization.1hey are completely responsi-
ble tor ensuring that the systems, the netvorks, and the applications are available to the users
during the hours needed by the users.
System Administrators pertorm a variety ot tasks including upgrading applications and
installing system sottvare, changing user passvords, monitoring the netvork tor bot-
tlenecks, and in some cases, changing printer toner cartridges. Some have to be on call
24 hours a day to provide support tor multiple shitt operations.
18 Chapter 1 IntroductIon to the OperatIng System nvIronment
UnderstandIng User Roles 19
System Administrators also maintain security, making sure users have the right access to
application tiles and tolders on the computer system. 1he goal is to give each user just
vhat is needed to do the job, but no more.
At times, a System Administrator may have to log in to a special user account that has
the ability to pertorm system administrative vork, such as add a print queue, change
another user`s passvord, or backup a system tile, standard user accounts don`t have the
ability to do these things. In Iinux, the name ot the user vith complete administrative
capability is called root.1he root user has access to programs and contiguration tiles that
standard users don`t.
You musL use cauLion when loin in as Lhe rooL user because you can deleLe
or modiy coniuraLion iles and prorams LhaL are unrecoverable wiLhouL
compleLely reinsLallin Lhe operaLin sysLem.
Depending upon the organization, the System Administrator may be responsible tor
vriting shell scripts, or the responsibility could be relegated to a shell programmer.
Shell Programmer
A shell progranner is responsible tor vriting shell scripts.A shell script is a program that
is vritten to automate a process in the Iinux operating system. A shell programmer vrites
the script using an editor, tests the script, and vhen the script passes the tests, makes the script
available to users.1he shell programmer must have an understanding ot programming con-
cepts as vell as the Iinux commands in order to successtully vrite scripts. lor example, a
shell programmer may need to vrite a script that uses system commands and decision logic
tor a System Administrator vho needs a vay to automate the backup process. Or a shell pro-
grammer may need to create a menu so several users can run Iinux commands vithout
entering the complete syntax ot the command.1ypically, a shell programmer logs in using a
regular user account unless the task requires them to use the root user account.
At times a shell programmer may have to debug scripts or remove any syntax or logic
error trom scripts or programs.A synta error is one that does not contorm to the rules
ot the language. An example ot a syntax error is a misspelled command. A compiler or
interpreter usually displays an error message vhen it encounters a syntax error. A script
or program can not run until it is syntax-error tree. Shell programmers must learn the
syntax ot the shell to prevent syntax errors.
1he Lerm debu was coined in Lhe 1940s when a moLh shorL-circuiLed elec-
Lrical componenLs in a mainrame compuLer sysLem causin a sysLem ailure.
8y removin Lhe moLh, Lhe sysLem was "debued."
A logic error is an error that does not meet the requirements ot the programming
logic as decided upon by the users and management. 1hese are typically more ditticult
tor the shell programmer to identity because the scripts are most likely syntactically
8MT
1
correct.1he compiler or interpreter does not display a message indicating the error and
the program appears to run normally. An example ot a logic error vould be using a
less-than symbol instead ot a greater-than symbol in an overtime calculation script. In
the tolloving set ot COBOI statements, a logic error occurs because the less-than sym-
bol is used in place ot the greater-than symbol. In the example, a person vorking more
than 40 hours vill have their pay calculated on regular time. 1he program vould run
because the use ot the less-than symbol is syntactically correct, but the output ot the
code vould be undesirable. Compare this example to the earlier COBOI example
vhere use ot the greater-than symbol (> 40, is logically correct.
IF HOURS < 40 THEN
PERFORM CALCULATE~OVER~TIME
ELSE
PERFORM CALCULATE~REGULAR~TIME
END~IF
9NDRS1ANDING &ASIC 0INUX 'OMMANDS
1he Iinux operating system contains numerous commands. Some are only available to
System Administrators and not to standard users, vhile other commands are available to
everyone.You need to learn about the commands that are available to all users because
they may also be used in shell scripts.
LoggIng In and LoggIng Out
One ot the tirst things you need to knov is hov to log in to the Iinux system.You need
a username and passvord. (1o complete the activities and projects in this book, you may
need to ask your instructor tor your username and passvord.,
1here are tvo vays ot logging in to a Iinux system. lirst, you can physically sit in tront
ot the system and enter you username and passvord. Second, you can use the telnet
command to log in to the Iinux system. 1his requires the host to have an IP address or
DNS name.
Next you vill log in using the second method just discussed.You vill use the ping com-
mand to verity the Iinux computer is accessible on the netvork and the telnet command
to connect to it it it is.You vill access the Iinux system trom a Windovs-based system that
is running 1CPIP.
1o verify the Linu host is accessible and connect to the Linu systen if it is:
1. Start Windovs on your computer (any version ot Windovs vill vork,.
2. Click the Start button, and then click Run. 1he Pun dialog box opens.
3. 1ype command, and then click OK. 1he Windovs command prompt opens.
20 Chapter 1 IntroductIon to the OperatIng System nvIronment
UnderstandIng asIc LInux Commands 21
4. 1ype ping hostnameZhostaddress, and then press Lnter. Be sure to
substitute your correct host`s name or IP address. It the command succeeded,
you should see a Peply trom message. It so, proceed to Step 6.
3. It you received an error, such as Pequest timed out, it means the host is
inaccessible. See your instructor. Do not go to the next step.
6. 1ype telnet hostnameZhostaddress, and then press Lnter. Be sure to
substitute your correct host`s name or IP address. 1he Iinux login prompt
appears. ligure 1-8 includes the logging-in process to the Iinux system trom
the Windovs command prompt.
7. 1ype your usernane, and then press Lnter.Your username appears on the
screen, and you are prompted tor a passvord.
8. 1ype your passvord, and then press Lnter.Your passvord vill not appear on
the screen tor security reasons.You have nov successtully logged in and have
access to the Iinux system.
9. 1o log out, type logout, and then press Lnter.Your connection to the
Iinux host is terminated, and you return to the Windovs command prompt.
AnoLher way Lo lo ouL is Lo press CLrl+D insLead o Lypin logout.
1he GEP Command
Once you`ve successtully logged in to the Iinux system, you can use other Iinux com-
mands. 1he cal command displays the current calendar month. Hovever, you can use
the cal command to display a variety ot months and years. Here is the general tormat
ot the command
cal month year
fIgure 1-8 Loin in Lo a Linux sysLem rom a Windows-based PC
8MT
1
1he month is an optional number betveen one and 12 representing the numeric num-
ber tor the month.You can only display the month it you include the year option.1he
year is an optional number betveen one and 9999 retlecting the year. So, tor example,
it you vant to display the current month`s calendar, you vould run this command cal.
1o display the calendar tor the vhole year, you vould run the cal command vith the
year only. lor example, the tolloving statement displays the calendar tor the tirst nine
months tor the year 2004.
cal 2004
ligure 1-9 shovs the partial calendar tor the year 2004.
1he GEX Command
1he cat command allovs you to display the contents ot text tiles very easily. You sim-
ply type in the command tolloved by the tilename, the text displays on your screen.
Atter the command completes its task, your prompt returns.
1he cat command is derived trom the term concatenate vhich means to join or tuse
together. 1he cat command concatenates the contents ot a tile on your disk vith the
screen. 1he command takes the tolloving torm
cat ot1on f11ename
Here is an example that displays the contents ot the sales tile
cat sales
fIgure 1-9 1he resulLs o Lhe cal2004 command
22 Chapter 1 IntroductIon to the OperatIng System nvIronment
UnderstandIng asIc LInux Commands 23
1he cat command not only allovs you to display text on the screen, but also allovs
you to create a tile. 1o do this you use the greater-than redirection operator, >. At this
point, all you need to understand is that the output ot the cat command is redirected
to a tile instead ot your screen. 1his results in the creation ot a nev tile.
1he concepL o redirecLion will be ully discussed in ChapLer 4.
Next you vill create a tile using the cat command and the redirection operator, and then
display the tile`s contents.
1o redirect tet to a file using the cat connand:
1. Iog in to the Iinux system as a user.
2. Pight-click a blank area ot the desktop, and then click Nev 1erninal. 1he
1erminal emulation program vindov appears vith your prompt.
3. 1ype cat > file2.txt, and then press Lnter. Notice that the cursor moves
to the beginning ot the next line and that there is no prompt on that line.
4. 1ype the tolloving code exactly as it is shovn, being sure to press Lnter at
the completion ot each line
Shell Programming will help me on the job.
Linux is fun!
When creaLin a ile wiLh Lhe cat command, once you've pressed LnLer aL
Lhe end o a line, you cannoL o back Lo LhaL line and ediL iL. CreaLin a ile
usin Lhe cat command is or quick Lasks. 1o ediL Lhe ile, you need Lo use one
o Lhe ediLors discussed laLer in Lhis chapLer.
3. Press Ctrl+D to send an end-ot-tile (LOl, character to the cat command.
1he cursor moves to the next line and your prompt returns.
6. 1o display the contents ot the tile, type cat file2.txt, and then press
Lnter. ligure 1-10 shovs the contents ot the tile you just created as vell as
your creation ot that tile.
7. 1o exit the vindov, type exit, and then press Lnter.
8. Iog out.
2SXI
8MT
1
1he HEXI Command
1he date command displays or sets the system date and time. Here is the general syn-
tax ot the command
date ot1on +format
1able 1-4 provides a listing ot available tormats tor the date command.
OptIon DescrIptIon xample
%D Displays Lhe daLe in NN/DD/YY ormaL; Lhis is where NN is Lhe date +%D
Lwo-diiL monLh, DD is Lhe Lwo-diiL day, and YY is Lhe lasL Lwo
diiLs o Lhe year
%d Displays Lhe Lwo-diiL day date +%d
%Y Displays Lhe our-diiL year date +%Y
%H Displays Lhe Lwo-diiL hour date +%H
%h Displays Lhe Lhree-leLLer monLh date +%h
%T Displays Lhe Lime date +%T
% Displays Lhe numeric day rom 001 Lo 366; Lhis is someLimes called date +%
Lhe Julian daLe
%m Displays Lhe Lwo-diiL monLh date +%m
1able 1-4 OpLions or Lhe date command
fIgure 1-10 1he cat command Lo creaLe a ile
24 Chapter 1 IntroductIon to the OperatIng System nvIronment
UnderstandIng asIc LInux Commands 25
ligure 1-11 shovs a screenshot ot the date command run using various tormats shovn
in 1able 1-4.
1he IGLS Command
You use the echo command to display text on the screen. As such, the echo command
is a very usetul debugging tool that can help you troubleshoot shell script programs.1he
echo command takes the torm ot the tolloving
echo "Text to d1s1ay"
While not required on all versions ot Iinux, on some versions you do need the quotes.
Hovever, it is good practice to enclose text that includes spaces in quotes.You vill learn
more about use ot quotes in Chapter 3. Consider this example
echo "How are you doing?"
You can use the echo command to create a tile. Hovever, using the echo command to
do this is only recommended vhen you only need a small tile consisting ot just a tev
lines. 1o do this you use the greater-than operator, >, to redirect the output trom the
screen to a tile. Pedirection vill be discussed in Chapter 4.
In the tolloving example, the output ot the echo statement is sent to a tile called sales
echo "March sales exceed proections for the Houston Branch
office." > sales
Next you vill use the echo command to redirect text to the sales tile, and then use the
cat command to display the contents ot the tile.
fIgure 1-11 1he date command run wiLh dierenL ormaLs
1
1o redirect tet to a file using the echo connand:
1. Iog in to the Iinux system as a user.
2. Pight-click a blank area ot the desktop, and then click Nev 1erninal. 1he
1erminal emulation program vindov appears vith your prompt.
3. 1o redirect the output to a tile named sales, type the tolloving code, and
then press Lnter
echo "March sales exceed projections for the Houston Branch
office." > sales
1he command executes but returns no output to the screen because the
output is redirected to the sales tile.
4. 1o display the contents ot the sales tile to your screen type cat sales.
ligure 1-12 shovs a screenshot ot the creation ot the sales tile using the
echo command and it`s displayed using the cat command.
3. 1o exit the vindov, type exit.
6. Iog out.
1he LMWXSV] Command
It you vant to see the commands you`ve already entered, you can run the history
command.1his command is usetul tor saving keystrokes.You can use your up and dovn
arrovs to go up and dovn through your history list to locate a command you previ-
ously entered. Once you locate the command you can use the backspace key to modity
it, or you can press Lnter to rerun the command as is.
fIgure 1-12 1he echo command used Lo creaLe Lhe sales ile
26 Chapter 1 IntroductIon to the OperatIng System nvIronment
UnderstandIng asIc LInux Commands 27
Here is the general tormat ot the command history
history ot1on
It you enter the history command vithout any options, it displays the last 1,000
commands you`ve entered. Lsed vithout any options, it can provide you vith more
intormation than you may be prepared to deal vith. Here are a tev vays you can use
the history command.
1he history command teature allovs you to enter a recently executed command by
placing the ! operator prior to the command. So, to rerun the most recently executed
cal command, enter
!cal
You don'L have Lo enLer Lhe compleLe command when usin Lhe ! operaLor.
For example, i you enLered, !da, Lhe mosL recenLly execuLed command LhaL
beins wiLh Lhe leLLers "da" is execuLed. l Lhe date command was Lhe mosL
recenLly execuLed command, Lhen iL would be rerun.
1he history command displays numbers to the lett ot each command in its list. It you see
a command in the history list that you vant to rerun, you can enter the ! operator tolloved
by the number ot the command in the list. So, to rerun the 1031
WX
command in the list, enter
!l03l
ligure 1-13 shovs a screenshot ot running the history command using the ! operator.
fIgure 1-13 1he history command usin Lhe ! operaLor
8MT
1
1he PTV Command
1he lpr command places a tile in the print queue tor printing.You use this command
to send a document to the printer.
1he tormat ot the command lpr is
lpr ot1on f11ename
1o print the sales tile you created in an earlier exercise, you enter the tolloving code
lpr sales
Although the lpr command prints to the detault printer set up by the System Administrator,
it can also be used to print to a specitic printer using the ~P option. lor example, to print
the sales tile to a printer named IinuxPrinter, enter lpr ~P LinuxPrinter sales.
NosL commands allow you Lo enLer opLions. However, because each command
has a dierenL uncLion, Lhe ormaLs o Lheir opLions are usually dierenL. For Lhe
mosL parL, an opLion is preceded by eiLher one or Lwo dashes, as in ~t.
1he QER Command
1he man command allovs you to display the manual, or help, pages tor a command.You
run this command to see a description ot a command and its options, it it has any. 1he
general torm is
man command
1o use the man command to display the manual pages tor the echo command, enter
man echo. ligure 1-14 shovs a screenshot ot the man pages tor the echo command.
fIgure 1-14 1he manecho command
DeLails Lhe opLions used by
Lhe command
Summarizes Lhe command
and any opLions or
daLa needed
Name o Lhe command
ollowed by a shorL
descripLion
8MT
28 Chapter 1 IntroductIon to the OperatIng System nvIronment
UnderstandIng asIc LInux Commands 29
1he XSYGL Command
1he main purpose ot the touch command is to update the moditication date and time
stamp ot a tile.1his is particularly usetul vhen vriting shell script programs. lor example,
it you had a shell script program that ran overnight or anytime vhen you veren`t avail-
able to check on it, you can ensure the script ran or the tile vas updated by running the
touch command tor the tile. 1he touch command takes the tolloving torm
touch f11ename
You can also use the touch command to create an empty tile and set the moditication
date and time on that tile using the same torm.
1he [LS Command
1he who command allovs you to display the list ot users vho are currently logged on
to the Iinux system. 1he torm ot the command is as tollovs
who ot1ons
You can also display a count ot the total number ot users logged in using the ~q option.
ligure 1-13 shovs a sample screenshot ot both the who and who ~q commands.
fIgure 1-15 1he who and who~q commands
1
Peter to 1able 1-3 tor a listing ot the common basic Iinux commands.
'RA1ING 7HLL 7CRIP1S
Because the shell is a command interpreter that makes use ot programming capabilities,
it allovs you to use traditional programming concepts. Here are some ot the traditional
programming concepts the shell allovs you to pertorm vith scripts
Make decisions based upon conditions
Pertorm arithmetic operations
Create a menu using looping statements
Lse tunctions to pertorm very specitic tasks
Manipulate data using an array
1he Lerms "scripL" and "proram" are synonymous.
A shell script pertorms one other tunction that traditional programming languages do not
typically support, the shell script runs operating system commands. Iike other programming
languages, you vrite your shell script, and then you execute it. Next you vill create a sim-
ple shell script.
8MT
Command DescrIptIon
cal Displays a calendar
cat Displays Lhe conLenLs o a ile
clear Clears Lhe screen
date Displays or seLs Lhe daLe and Lime
echo Displays LexL
history Displays previously enLered commands
login and logout Allows you Lo lo in and lo ouL
lpr PrinLs a ile
man Displays manual (help) paes or a command
ping DeLermines i anoLher 1CP/lP sysLem is available
telnet ConnecLs Lo a 1CP/lP compuLer
touch UpdaLes Lhe modiicaLion daLe and Lime o a ile
who Displays Lhe currenLly loed on users
1able 1-5 8asic Linux commands
30 Chapter 1 IntroductIon to the OperatIng System nvIronment
CreatIng Shell ScrIpts 31
1o create and eecute a sinple shell script:
1. Iog in to the Iinux system as a user.
2. Pight-click a blank area ot the desktop, and then click Nev 1erninal. 1he
1erminal emulation program vindov appears vith your prompt.
3. 1ype cat > script1, and then press Lnter to create a tile called script1.
4. 1ype the tolloving code to add text to script1
echo "Welcome to my shell script."
echo "This is one of my first shell scripts!"
echo "Shell script programming is a tool for helping users
automate their tasks."
3. Press Crl+D to terminate the line.Your prompt returns.
6. 1o execute the script, type bash script1, and then press Lnter.Your
screen should look like ligure 1-16 vhich shovs the script you have input as
vell as the resulting output.
7. 1o exit the 1erminal emulation program, type exit, and then press Lnter.
8. Iog out.
1o reintorce vhat you`ve already learned about using commands and creating shell
scripts, next you vill create a shell script that displays the calendar tor the current month,
the current time on the screen, and the usernames ot the users currently logged in.
fIgure 1-16 scripL1 and resulLin ouLpuL
1
1o create a shell script vhich displays the calendar, the current tine, and the
usernanes of those users currently logged in:
1. Iog in to the Iinux system as a user.
2. Pight-click a blank area ot the desktop, and then click Nev 1erninal. 1he
1erminal emulation program vindov appears vith your prompt.
3. 1ype cat > script2, and then press Lnter to create a nev tile named
script2.
4. 1ype cal, and then press Lnter to include the current calendar.
3. 1ype date, and then press Lnter to include the current date.
6. 1ype who, and then press Lnter to display the users that are currently logged
in. Press Crl+D to terminate the line. 1he prompt returns.
7. 1o execute the script, type bash script2, and then press Lnter.Your
screen should look like ligure 1-17 vhich displays the script you have input
as vell as the resulting output.
8. Pecord the output.
9. 1o exit the 1erminal emulation program, type exit, and then press Lnter.
10. Iog out.
fIgure 1-17 scripL2 and resulLin ouLpuL
32 Chapter 1 IntroductIon to the OperatIng System nvIronment
Chapter Summary 33
'HAP1R 7UMMARY
1he operating system is the sottvare brains that manage the computer system.
1he operating system interacts vith users, the applications, and the hardvare. All
computer systems must have an operating system in order tor the system to run.
1he Iinux operating system is a portable, multiuser, multitasking, and multiprocessing
system. Iinux supports both a graphical user intertace (through the use ot X Windovs,
or a text mode intertace.1here are numerous versions ot Iinux in the marketplace.
1he Iinux shell interprets shell scripts.
Sottvare can be classitied into systems sottvare and application sottvare. System
sottvare includes the kernel, job management sottvare, memory management sott-
vare, and device drivers. System utilities include backup and restore sottvare, com-
pression and uncompression sottvare, tile system management sottvare, and printer
management sottvare. 1he kernel is the nucleus ot the operating system. It remains
in memory and controls other sottvare components.
Data is made up ot rav tacts. Intormation is processed data. A bit is either a binary
zero or one. A byte is a group ot eight bits. A tield is a group ot bytes. A record is a
group ot tields. A primary key tield is a special tield that allovs you to quickly
access a record in a tile. A tile is a group ot records. 1here are tvo types ot tiles
executable, or binary, and nonexecutable. Lxamples ot executable tiles are com-
mands and programs. Lxamples ot nonexecutable tiles are picture tiles or text tiles.
It is important to understand the user roles in a Iinux environment so you can cre-
ate appropriate scripts and access to the system tor the user. A standard user is a
person vho uses the application and system on a daily basis to pertorm a certain
job tunction such as payroll, accounting, marketing, tinance, or engineering. A
System Administrator is responsible tor maintaining, monitoring, upgrading, and
troubleshooting the system and netvork so users can do their jobs. A shell pro-
grammer vrites shell programs tor users. Shell programmers apply their knovledge
ot programming logic and Iinux commands to create scripts tor users.
Iinux allovs you to interact vith the operating system via commands.1here are liter-
ally hundreds ot commands. Most have multiple options that augment the command in
some vay.You use the manual pages tor the command you vant to learn more about.
Shell script programming combines programming logic structures vith operating
system commands to automate routine tasks. 1he shell runs commands in the shell
program.
1
6VIW 5US1IONS
1. is the sottvare that remains in memory and controls other
activity.
a. Kernel
b. Sottvare utilities
c. Backup sottvare
d. ob management sottvare
2. Shell script programs usually run in the mode ot Iinux.
a. X Windovs
b. MS Windovs
c. graphical
d. text
3. Which ot the tolloving is an interpreted language
a. COBOI
b. C
c. C
d. Bourne-Again Shell (bash,
4. A spreadsheet is an example ot sottvare.
a. backup
b. application
c. print management
d. assembly language
3. A group ot tields is also knovn as a .
a. byte
b. character
c. record
d. table
6. Hov many bits are in a byte
a. 1
b. 2
c. 4
d. 8
34 Chapter 1 IntroductIon to the OperatIng System nvIronment
RevIew QuestIons 35
7. What company tirst developed LNIX
a. Microsott
b. Iinux
c. Ped Hat
d. A181
8. is another name tor a process.
a. ob
b. Disk drive
c. lolder
d. X Windovs
9. Which command allovs you to display the manual pages tor a command
a. man
b. pages
c. who
d. lpr
10. When vas LNIX developed
a. 1960s
b. 1970s
c. 1980s
d. 1990s
11. Which command allovs you to display the tvo-digit day
a. date +%Y
b. date +%T
c. date +%d
d. date +%D
12. is rav tacts
a. Intormation
b. ob
c. Data
d. Daemon
1
13. is a background job.
a. Intormation
b. ob
c. Data
d. Daemon
14. 1he command sends a document to the printer.
a. lpr
b. printit
c. date
d. echo "Hi" > file4.txt
13. A is a group ot related records.
a. tield
b. tile
c. bit
d. character
16. A is a person vho uses the system on a daily basis to do his
specitic job, such as manutacturing, accounting, or payroll.
a. System Administrator
b. standard user
c. shell programmer
d. daemon
17. A is a person responsible tor making sure the systems and net-
vorks are available to the users vhen needed.
a. System Administrator
b. standard user
c. shell programmer
d. job
18. A picture tile is an example ot a tile.
a. binary
b. executable
c. nonexecutable
d. job management
36 Chapter 1 IntroductIon to the OperatIng System nvIronment
Hands-on Projects 37
19. A command is an example ot a tile.
a. binary
b. nonexecutable
c. print queue
d. X Windovs
20. A is a person vho vrites scripts as his or her main job tunction.
a. System Administrator
b. standard user
c. shell programmer
d. print queue
,ANDSON 4ROJC1S
Project 1-1
In this project, you vill visit an organization that uses the Iinux operating system and
discuss the type ot hardvare and sottvare it uses. You`ll also record it the organization
uses any scripts, and it so, tor vhat purpose.
1. Iocate an organization that uses the Iinux operating system as the main operating
system tor their organization.
2. Pecord the name ot the organization.
3. Interviev one ot the System Administrators or other persons responsible tor the
computer system. Pecord the type ot hardvare used.
4. Pecord the version ot Iinux used.
3. Pecord the application sottvare used.
6. Pecord the shell interpreter used by their users.
Project 1-2
In this project, you vill visit various Iinux vendor Web sites and record your tindings.
1o complete this project, you vill need Internet access.
1. Open your Web brovser, then go to the redhat.con Web site.
2. Spend some time brovsing this Web site.
3. Pecord intormation about cost, hardvare requirements, sottvare version, and
product otterings ot the Ped Hat version ot Iinux.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
1
4. Change the address location to the calderasystens.conWeb site.
3. Spend some time brovsing this Web site.
6. Pecord intormation about cost, hardvare requirements, sottvare version, and
product otterings ot the Iinux version ottered by Caldera.
7. Change the address location to the nandrake.conWeb site.
8. Spend some time brovsing this Web site.
9. Pecord intormation about cost, hardvare requirements, sottvare version, and
product otterings ot the Iinux version ottered by Mandrake.
Project 1-3
In this project, you vill execute basic Iinux commands to help you understand hov to
interact vith the operating system shell.
1. Iog in to the Iinux system as a user.
2. Open a 1erminal emulation vindov.
3. 1ype who, and then record the output.
4. 1ype cal, and then record the output.
3. 1ype date, and then record the output.
6. 1ype history, and then record the output.
7. 1ype !# vhere = is a number in the history list ot a command you vant to execute.
8. Pecord the command that vas used.
9. Lse the up and dovn arrov keys to scroll back and torth in the history list ot
recently executed commands, and press Lnter to execute a command.
10. Pecord the command.
11. 1o exit the 1erminal emulation program, type exit.
12. Iog out.
Project 1-4
In this project, you vill execute ditterent variations ot the commands to help you under-
stand hov to run commands using ditterent options.
1. Iog in to the Iinux system as a user.
2. Open a 1erminal emulation vindov.
3. 1ype date +%h, and then record the output.
4. 1ype date +%T, and then record the output.
3. 1ype date +%m, and then record the output.
6. 1ype who -g, and then record the output.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
38 Chapter 1 IntroductIon to the OperatIng System nvIronment
Hands-on Projects 39
7. 1ype cal month year vhere month is your tvo-digit birth month and ear is
your tour-year birth year, and then record the day ot the veek you vere born on.
8. 1o exit the 1erminal emulation program, type exit.
9. Iog out.
Project 1-5
In this project, you vill vrite a small shell script to display text on the screen.
1. Iog in to the Iinux system as a user.
2. Open a 1erminal emulation vindov.
3. 1ype cat > Project1-5.
4. 1ype the tolloving code to insert text into the Project1-3 script
echo "Welcome to my shell script."
echo "This is one of my first shell scripts."
echo "Shell script programming is a tool for helping System
Administrators."
3. Send an end-ot-tile (LOl, character to the cat command.
6. 1o execute the script, type bash Project1-5.
7. 1o print your script to the detault printer, type lpr Project1-5. It you don`t have
access to a printer, record vhat displays on the screen on a separate sheet ot paper.
8. 1o exit the 1erminal emulation program, type exit.
9. Iog out.
Project 1-6
In this project, you vill vrite a shell script to display the current ulian date and the
number ot users currently logged in.
1. Iog in to the Iinux system as a user.
2. Open a 1erminal emulation vindov.
3. 1ype cat > Project1-6.
4. 1ype date +%j.
3. 1ype who -g.
6. Send an end-ot-tile (LOl, character to the cat command.
7. 1o execute the script, type bash Project1-6.
8. Pecord the output.
9. 1o print your script to a specitic printer, type lpr ~P printer-
name Project1-6 vhere printer-name is the name ot the printer.You may
have to get the printer name trom your instructor.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
1
10. Close your 1erminal emulation vindov.
11. Iog out.
Project 1-7
In this project, you vill use the manual pages to help you locate a particular option.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1ype man cat.
3. Iocate the option to number all output lines, and then record the letter tor
that option.
4. 1o use the option, type cat ~option Project1-6 vhere option is the letter
you recorded in the previous step. (Iine numbers display to the lett ot the com-
mands in the previous script tor the previous project.,
3. 1ype man lpr.
6. Pead through the man pages and tind a nev option tor the lpr command that has
not been discussed in this chapter, and then record the option and its description.
7. 1ype man touch.
8. Pead through the man pages and tind an option tor the touch command, and
then record the option and its description.
9. Pun the command using the option you chose, and then record the command
and the option you chose.
10. Close your 1erminal emulation vindov.
11. Iog out.
Project 1-8
In this project, you vill create a script containing three statements. You vill insert dit-
terent versions ot the date command using various options.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Lse the cat command to create a tile named Project1-8. (HintYou need to use
the redirection symbol.,
3. Lsing the correct option trom 1able 1-4, insert the date command so it displays
the date in MMDDYY tormat.
4. Lsing the correct option trom 1able 1-4, insert the date command so it only
displays the current time.
3. Send an end-ot-tile (LOl, character to the cat command.
6. Display the contents ot the Project1-8 script, using the cat command.
7. Pecord the contents ot the script.
8. Lxecute the script using the bash command.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
40 Chapter 1 IntroductIon to the OperatIng System nvIronment
Case Projects 41
9. Print your script. It you do not have access to a printer, record vhat displays on
your screen on a separate sheet ot paper.
10. Pecord the command needed to print the script.
11. Close the 1erminal emulation vindov.
12. Iog out.
'AS 4ROJC1S
Case 1-1
1MI Corporation is currently running maintrame computers in a distributed environment.
1here are about 23 users connecting via dumb terminals to the main ottice, located in
Iavrenceville, Georgia.1hey use manutacturing, inventory, and personnel applications vrit-
ten in COBOI. 1heir programmers are villing to learn other languages but have not yet
had the chance because they`ve been too busy maintaining the current applications. 1he
company has outgrovn its computing resources. It is in the process ot selecting an entirely
nev computer systemtrom hardvare to sottvare.
Write a proposal to the company`s chiet intormation otticer (CIO, convincing her to
choose the Iinux operating system. Include specitications tor the 1MI Corporation,
accounting tor enough computers to service the current number ot users, tvo servers,
and tive printers. Indicate the programming language the nev applications should be
vritten in and support your decision. Include a rationale tor sending tvo System
Administrators to attend Iinux administration classes.
Case 1-2
1he Daisy Mae Woo Haberdashery Corporation currently is running a proprietary
LNIX operating system trom the XYZ Corporation vendor. 1he XYZ Corporation is
going out ot business because ot a dovnturn in the economy. 1he Daisy Mae Woo
Haberdashery`s business is thriving, but they are vorried about the potential lack ot sup-
port in the tuture. 1he Daisy Mae Woo Haberdashery has tive remote ottices located
vithin 10 miles ot its main ottice.1he Daisy Mae Woo Haberdashery has tinancial appli-
cations running in C and many ot the System Administration tools are vritten in the
Bourne Shell. Many times, the sottvare locks up the computer system causing it to halt.
So, a nev operating system is needed. 1he current version ot LNIX is compatible vith
versions ot MINIX.
1he Daisy Mae Woo Haberdashery Corporation has decided to go vith a nev vendor,
the Alpha lirm, tor consulting services. Write a proposal to 1he Daisy Mae Woo
Haberdashery Corporation as it you vere a vice president tor the Alpha lirm. Include
in your proposal vhich version ot Iinux you vould recommend, the shell you vould
support, and hov you vould go about migrating the current programs to the nev sys-
tem. Detend your decision on paper.
'EWI
4VSNIGXW
'EWI
4VSNIGXW
1
43
',%48)6

92()678%2(-2+ 8,) 0-29<


*-0) 7=78)1
-RXLMWGLETXIV]SY[MPP
9RHIVWXERHXLI0MRY\XVIILMIVEVGL]
2EZMKEXIXLIXVIILMIVEVGL]
9RHIVWXERHHMVIGXSV]QEREKIQIRXGSQQERHW
9WIIHMXMRKGSQQERHW
9RHIVWXERHJMPIQEREKIQIRXGSQQERHW
-
n this chapter, you vill gain an understanding ot the Iinux tile system.You
vill learn its purpose and hov to navigate and manipulate it.You vill also
learn about some editors you can use to accomplish a variety ot tasks, as vell
as various Iinux commands you need to accomplish these goals.
9NDRS1ANDING 1H 0INUX 8R ,IRARCHY
1he Iinux tile system is based upon a tree hierarchy. Iike other hierarchies, an order
exists vithin the tree.1here is a top level vith other sublevels branching beneath it.1he
tree hierarchy otters storage and quick access.
Storage
Storage vithin the Iinux tile system is accomplished vith tvo main elements directo-
ries and tiles. Directories are considered holding areas or containers. lrom a user`s
standpoint, directories can contain tiles and other directories, sometimes called subdi-
rectories. liles contain datatext, binary intormation, picture images, and other types
ot intormation. liles are stored in directories. 1ypically, tiles that are alike are stored
vithin one directory. While a directory can contain multiple directories and tiles, tiles
themselves cannot contain directories or other tiles.
1he Linux operaLin sysLem LreaLs every sLorae componenL such as a direc-
Lory or a ile as a JMPI. Files conLain Lhe daLa you need. DirecLories are simply
a means o roupin Lhe iles.
At the top ot the Iinux tree is a single directory called root. 1he root directory is vhere
all other tiles and directories in the tile system stem trom. 1he root directory is created
during installation ot the operating system and cannot be changed or deleted vithout los-
ing the operating system and related tiles.1he symbol tor the root directory is the torvard
slash (,.You must use this symbol vhen accessing the root, or top-level, directory.
8oLh iles and direcLories are ulLimaLely sLored on disk.
QuIck Access
Generally, vhen you create directories, you group and store similar tiles together.1his directly
benetits you and also translates to quicker access vhen you need to tind a tile. It you knov
vhat type ot tile you are looking tor, you can go straight to the directory in vhich it is
located. Consider this example.You vork in the payroll department tor 1ovnsend 1oyota and
you are responsible tor making sure payroll goes out on a monthly basis. Because the com-
pany pays its employees monthly, you have tvelve payroll tiles.1he tiles are named an.dat,
leb.dat,Mar.dat, and so on. Hov vould you organize these in the tree You could put
them in separate directories or even scattered in a directory vith other unrelated tiles.
8MT
8MT
44 Chapter 2 UnderstandIng the LInux fIle System
UnderstandIng the LInux 1ree HIerarchy 45
Hovever, vhen you try to locate them, you may not be able to tind them quickly because
they are not organized in a central location. A better design is to create a directory named
Payroll and place all the monthly payroll tiles in it.1hen, near payday, you simply look in the
Payroll directory, tind the tiles you need, and process the payroll data.
As another example, it you had several tiles dealing vith your personal intormation, you
might create a directory called Personal and place your resume, sample cover letters,
school documents, and e-mail messages in that directory. Lltimately, it is easier tor you
to tind the tiles because you have organized them.
1he "Garden Store 1ree" Analogy
1he Iinux tile system hierarchy is analogous to an actual tree you might purchase at a
garden store that has its root system vrapped in canvas. It you turn that garden store tree
upside dovn in your mind, you have the concept ot the Iinux tree hierarchy. 1he root
system is nov at the top, just like the Iinux root directory.1he branches and leaves stem
trom the root. A directory in Iinux is analogous to a branch on the garden store tree. A
leat is analogous to a tile because a leat cannot contain branches or other leaves just as
a tile cannot contain directories or other tiles, hovever, a tile does have contents. ust as
a directory can contain other subdirectories and tiles, a branch can contain other
branches and leaves.
Consider this example. 1ovnsend 1oyota has a Iinux system vhich contains tiles and
directories. It has created directories to represent its business departments.1here are tiles
vithin the directories that contain business-related data. ligure 2-1 shovs the tree struc-
ture ot 1ovnsend 1oyota. 1he tree command displays a hierarchical listing ot the
directory. Notice that the root, (,, directory is near the upper-lett corner.1he directories
and tiles are organized into logical groupings beneath the directory named
1ovnsend1oyota vhich is immediately beneath the root, (,. 1he directories named
Accounting, I1, Marketing, and Production are on the same level, talling immediately
vithin the 1ovnsend1oyota directory. Iook at the Accounting directory and see the tour
directories beneath itAccountsPayable, AccountsPeceivable, GeneralIedger, and
Payroll. Pecall that the directory named Payroll contains the payroll tiles mentioned in
the previous example.
You can use Lhe tree command Lo show a snapshoL o a subdirecLory Loo. l
you wanL Lo see Lhe Lree sLrucLure jusL or Lhe direcLory named NarkeLin,
you enLer treeMarketing. 8MT
2
1he tree command is usetul tor shoving the tree structure, hovever, vhen vriting
shell programs, you need to understand hov to get to those tile or directories vithin
the tree. It you vanted to access the May.dat tile trom the root directory, you vould have
to tollov the lines in ligure 2-1 dovn and over to the right until you tinally got to the
tile. You vould end up going through the 1ovnsend1oyota, Accounting, and Payroll
directories, respectively.
You can Lhink o Lhe ouLpuL o Lhe tree command as a map Lo eL Lo a ile
or direcLory. A map shows you Lowns you musL o Lhrouh Lo eL Lo your
desLinaLion. 1he tree command shows you Lhe direcLories you musL o
Lhrouh Lo eL Lo your iles.
LInux System DIrectorIes
Iinux stores many ot its system tiles in various subdirectories beneath the root directory.
1hese are created during installation ot the operating system and should not be deleted
or renamed.You need to understand the purpose ot the Iinux system directories, shovn
in 1able 2-1, in case your scripts reter to commands or tiles contained vithin them.
8MT
fIgure 2-1 1ree hierarchy or 1ownsend 1oyoLa
46 Chapter 2 UnderstandIng the LInux fIle System
NavIgatIng the 1ree HIerarchy 47
2AVIGA1ING 1H 8R ,IRARCHY
Nov that you understand hov the hierarchy is set up, you need to learn hov to nav-
igate the Iinux tile system. Iook at the sample hierarchy tree shovn in ligure 2-2,
the top-level directory is root, shovn by the torvard slash symbol, (,. Other directo-
ries branch beneath it. Lnder the user`s home directory, represented by the variable
$HOME, the directories named dirA and dirB exist. A variable is used tor tlexibility, so
that users and shell scripts can reter to $HOME, and it equates to their individual home
directory. Beneath each ot these are other directories. Lltimately, tiles are stored at the
bottom ot the tree. Directories on the same level and having the same parent direc-
tory are considered sibling directories. Said another vay, dirA and dirB are child
directories ot $HOME, their parent.
DIrectory Purpose
/bin Holds many binary execuLable prorams
/booL Holds Lhe Linux kernel
/dev ConLains device iles or all Lhe devices in Lhe Linux ile sysLem
/eLc Holds coniuraLion iles; many are wriLLen usin shell scripL prorams. ConiuraLion iles
are iles LhaL various prorams read in order Lo know whaL Lhey are supposed Lo do.
/home DeaulL locaLion which conLains user direcLories; when users lo in Lo a Linux sysLem,
Lheir currenL direcLory is /home/YWIVREQI. For example, a user named Narissa has a
home direcLory o /home/marissa.
/lib ConLains iles and execuLable prorams used by Lhe sysLem
/mnL ConLains mounLed drives
/rooL 1he Linux superuser, or rooL user's home direcLory
/sbin ConLains addiLional binary execuLable prorams normally used by Lhe rooL user
/Lmp Used or Lemporary ile and direcLory sLorae
/usr ConLains oLher subdirecLories or applicaLions, such as X11 (or X Windows on Linux),
H1NL iles, library iles, and ames; also included are header iles or C prorams.
1wo o Lhe mosL widely used subdirecLories wiLhin /usr are usr/bin and /usr/sbin.
1hese conLain direcLories and binary execuLables.
/var ConLains boLh iles and direcLories; Lypically, Lhe Lype o iles in /var vary in size,
such as Lhe lo iles or various processes locaLed in /var/lo. 1he sysLem lo ile,
/var/lo/messaes, is also held here.
1able 2-1 Some o Lhe Linux sysLem direcLories
2
When a user account is created, a home directory is automatically created tor that user.
1he home directory is usually located in home as described in 1able 2-1. 1he system
uses a variable named $HOME vhich equates to your home directory.
1he contents ot the variable named $HOME is ditterent tor each user. It is just a method
ot saying your ovn home directory. lor example, Mary Phan`s $HOME may literally be
equal to homemaryphan, vhile Harold Patel`s $HOME directory may literally be equal
to homeharoldpatel.
Your current directory denotes vhere you are vithin the tile system. 1hink ot it as
vhere you are in a building vhen looking at a building evacuation map. 1he makers ot
the map assume you are in a certain room vhen they created the evacuation plan. 1hey
even have a red You Are Here dot vith a red arrov representing a path shoving hov
to exit the building. 1he Iinux tree operates similarly. 1he You Are Here dot repre-
sents your current directory and the long red arrov represents hov to get to another
location, such as another directory.
When navigating you need to knov tvo thingsvhere you are and vhere you vant
to go vithin the tree hierarchy.
$HONL
RooL
dirA dir8
dirA1 dirA2
l.daL 2.daL 3.daL
dir81 dir82
DirecLories
Files
4.daL 5.daL 6.daL 7.daL 8.daL
fIgure 2-2 A sample Lree hierarchy
48 Chapter 2 UnderstandIng the LInux fIle System
NavIgatIng the 1ree HIerarchy 49
ChangIng DIrectory LocatIons
It you vant to change your current position to the root directory, you have to use the
cd command.1his command allovs you to change directory locations vithin the tree
to another directory. It takes the general torm
cd d1rectory
1hink o Lhe cd command as chanin your "You Are Here" locaLion in Lhe Lree.
1he d1rectory is a directory location vithin the tree that you vant to go to.
1o help you navigate through the tree, you need to understand the terms tull path and
partial path. 1he full path specities the complete path trom root. A tull path alvays
begins trom the root directory. 1he partial path specities a certain point in the direc-
tory path, vhich is simply the name ot the directory that you vould like to change to
relative to your current location. It never begins at root.
1he ull or parLial paLh can be used wiLh mosL any command.
Imagine someone asks you tor directions trom his house to your house.You vould give him
directions that vould take him trom his tront door to yours. Lssentially, you vould be pro-
viding him vith the tull path. It that same person vas already on the vay to your house and
perhaps became lost, you vouldn`t give them the tull path directions, instead you vould pro-
vide directions relative to vhere he currently is located, in other vords, the partial path.
ChangIng DIrectory LocatIons to the / DIrectory
Assume your current directory is dirA in ligure 2-2. In order to change to the root
directory using a tull path, you vould issue this command
cd /
ligure 2-3 shovs changing directory locations to the root directory. Notice that the
betore the cd command is pertormed, the user is in the toddm directory.
8MT
8MT
2
ChangIng DIrectory LocatIons to a Parent DIrectory
In order to change to a parent directory, you use a special notation. In Iinux, the par-
ent directory is represented by the use ot tvo dots (.., notation. Iet`s say your current
directory is dirA1 as shovn in ligure 2-2. 1he command to navigate to the parent
directory, dirA is
cd ..
1he use ot the tvo dots, .., is an example ot a partial path. Lvery directory, except the root
directory, has a parent directory, or ... 1he root directory cannot have a parent directory
because it is the top directory. A vay you can remember this is that you have tvo parents,
one mom and one dad, and in the tree hierarchy, they are collectively reterred to as the
parent. ligure 2-4 shovs changing directory locations to the parent directory.
ChangIng DIrectory LocatIons to a ChIld DIrectory
In order to change directory locations to a child directory, you reter to the child by its
name. Here is the general torm
cd ch11d~d1rectory
1his is vhere ch11d~d1rectory is the name ot the child directory you vant to
change directory locations to. It you vant to change trom the current directory ot dirA
to one ot its child directories, such as dirA1, as shovn in ligure 2-2, you vould issue
this command
cd dirAl
fIgure 2-3 Runnin Lhe cd Lo chane Lhe rooL direcLory
Command
DirecLory you are
chanin Lo
CurrenL direcLory
50 Chapter 2 UnderstandIng the LInux fIle System
NavIgatIng the 1ree HIerarchy 51
ligure 2-3 shovs changing directory locations to a child directory
ChangIng DIrectory LocatIons to a SIblIng DIrectory
A sibling directory is a peer directory ot your current directory. In ligure 2-2, the direc-
tories dirA and dirB are sibling directories. Also, dirA1 and dirA2 are siblings, as vell as
fIgure 2-5 Chanin Lo a child direcLory usin Lhe cd command
Command
DirecLory you are
chanin Lo
CurrenL direcLory
fIgure 2-4 Runnin Lhe cd.. command Lo naviaLe Lo a parenL direcLory
Command
DirecLory you are
chanin Lo
CurrenL direcLory
2
dirB1 and dirB2. Hovever, even though dirA1 and dirA2 are on the same level as dirB1
and dirB2 they are not siblings because they have ditterent parents.
1o change to any sibling directory, the syntax is
cd ../s1o11ng
Assume your current directory is dirB, and you vant to change directory locations to
dirA.You vould use the code
cd ../dirA
In the command, cd ../dirA, the tvo dots represent the parent directory, in this case
$HOME, and the torvard slash is a separator betveen the parent and child levels ot root
and dirA. ligure 2-6 shovs changing directory locations to a sibling directory.
ChangIng DIrectory LocatIons Across MultIple Levels
In order to change directory locations across multiple levels you reter to each parent in
the hierarchy tree. Here is the syntax
cd ../../d1rectory
It your current directory is dirA1 as in ligure 2-2, you navigate to dirB as tollovs
cd ../../dirB
1he tirst pair ot dots represents the parent ot dirA1 vhich is dirA.1he second pair ot dots
represents the parent ot dirA vhich is $HOME.1his happens to be the grandparent ot dirA1.
linally, you include the directory name you vant to navigate to that is multiple levels avay,
fIgure 2-6 Chanin Lo a siblin direcLory usin Lhe cd command
Command
DirecLory you are
chanin Lo; noLice LhaL
Lhe paLh is Lhrouh Lhe
parenL direcLory
CurrenL direcLory
52 Chapter 2 UnderstandIng the LInux fIle System
UnderstandIng DIrectory Management Commands 53
vhich in this case is dirB. ligure 2-7 shovs changing directory locations across multi-
ple levels.
9NDRS1ANDING (IRC1ORY 1ANAGMN1 'OMMANDS
In order to be a proticient Iinux System Administrator, you must be avare ot many ot
the commands used to manage the Iinux tile system. Lach command executes and gen-
erates one ot the tolloving
^o output1he command vorked successtully.
utput1he command vorked successtully.
n error1he command did not vork correctly.
1he Iinux commands are divided into three main categories
Dire.tor .ommanosCommands that vork vith directories
Loitor .ommanosCommands that allov you to manipulate the tile system
Iiie .ommanosCommands that vork vith tiles
1he main commands that deal vith directories are summarized in 1able 2-2. 1hese are
the most commonly used commands relating to the tile system. It is important that you
learn these commands because they allov you to manage the Iinux tile system, and
understanding them gives you greater control over the tile system.
fIgure 2-7 Chanin direcLories across mulLiple levels
Command
DirecLory you are chanin
Lo; noLice LhaL Lhe paLh
oes Lhrouh Lhe parenL
and randparenL direcLories
CurrenL direcLory
2
1he T[H Command
1he pwd command displays your current vorking directory and returns output to the
screen. Although it does not have very many practical options, it is one ot the most
important commands because it lets you knov vhere you are in the tree hierarchy. 1o
execute the command, you simply type pwd on the command line, and then press Lnter.
1his displays your current directory location on the screen.
1he PW Command
1he ls command lists a directory`s contents.You use this command to determine vhat
is in a directory. 1he ls command has a variety ot uses and many ditterent options tor
listing directories. lor example, it you vanted to see the size ot a tile in bytes, you vould
attach the appropriate option to the ls command. Iike the other directory commands,
the command is vritten
ls ot1on ath~name
1he symbol tor indicating an option is typically either a single dash (-, or a double-dash
(--,, and it is tolloved by the option. So, the ~l option vhen attached to the ls com-
mand as in ls ~l gives additional intormation about the tiles and directoriessuch as
the size ot the tiles and the permissions.
1he command ls~l uses a lowercase leLLer l (as in lucky), noL Lhe numeral
one. Don'L make Lhe misLake o puLLin a one aLer Lhe dash symbol; iL resulLs
in an error.
1he path name is optional. It you leave it ott, the ls command detault is to shov you
the contents ot the current directory.
1he -l OptIon on the ls Command
One ot the most common options tor the ls command is ~l vhich is short tor long
listing.1he term long listing means that more intormationtype ot tile, permissions,
links, ovner, group, size in bytes, date and time, and nameis displayed on the screen
8MT
DIrectory Command Purpose
pwd Displays Lhe name o your currenL direcLory
ls Displays boLh iles and direcLories; by deaulL, iL displays Lhe iles and
direcLories in Lhe currenL direcLory
cd Chanes direcLory locaLions
mkdir CreaLes or makes a direcLory
rmdir DeleLes or removes a direcLory
1able 2-2 DirecLory commands
54 Chapter 2 UnderstandIng the LInux fIle System
UnderstandIng DIrectory Management Commands 55
vhen you use this option than it you don`t. ligure 2-8 shovs the output ot the ls
command vith the ~l option. 1able 2-3 provides an overviev ot the various tields
represented in the tigure.
1he 1ype Column 1he tirst tield ot the long listing tormat is the 1ype tield. 1able 2-4
provides a listing ot the various types ot items that can appear here.
1ype Value DescrIptIon
d File is a direcLory
- File is a ile
c File is a characLer device
b File is a block device
1able 2-4 Possible values o Lhe Lype ield o Lhe lon lisLin
1ype PermIssIons LInks Owner Group SIze In ytes Date and 1Ime Name
d rwxrwxr-x 2 Loddm Loddm 4096 Au 30 20:52 dir1
- rw-rw-r-- 1 Loddm Loddm 37 Au 31 6:48 1.daL
- rw-rw-r-- 1 Loddm Loddm 102 Au 31 6:48 2.daL
1able 2-3 1able o Lhe column ields in a lon lisLin
fIgure 2-8 OuLpuL o Lhe ls~l command
2
1he PermIssIons Column 1he next nine characters atter the tile type represent
permissions tor the tile or directory. 1hese are grouped into three sets ot three. 1he
tirst three characters represent permissions tor the ovner, the second set ot three
characters represents permissions tor the group, and the last set ot three characters
represents permissions tor other users, commonly knovn as the vorld.1able 2-3 pro-
vides comprehensive detinitions ot the permissions.
Note that the permissions are positional. 1hey are alvays in this order read, vrite, and
execute. It a dash exists in place ot the permission, then the permission is turned ott or
not available. lor example, it the permissions are r-x, then the permissions are tor read
and execute, but no vrite permission is given.
AddItIonal Columns 1he remaining six columns are a bit more straighttorvard in
their presentation. 1he Iinks column represents the number ot links or shortcuts to the
tile or directory. 1he Ovner column represents the actual user vho ovns the tile.
Generally, this is the person vho created it. Notice that toddmis the ovner.1he ovner
ot the tile or directory receives the ovner set ot permissions (the tirst set ot read, vrite,
and execute permissions atter the 1ype tield,. 1he Group column represents the group
membership. It a user is a member ot the group, they get the group set ot permissions
(the middle set ot read, vrite, and execute permissions, in the permissions tields. It you
are not the ovner or a member ot the group, then you get the last set ot permissions.
1he Date and 1ime column is the date and time stamp the tile or directory vas created.
1he Size in bytes column is the size ot the tile or directory. And tinally, the Name col-
umn is the Iinux name used vhen reterring to the tile. A Iinux tilename can be no
more than 236 characters long.
1he -a OptIon on the ls Command
1he ~a option is used to display all tiles and directories. What makes it ditterent trom
the ~l option is that it is used to display hidden tiles in your ovn directory. Hidden tiles
begin vith a dot or period. Knoving hov to list hidden tiles can be very usetul. You
may tind it necessary to hide tiles in order to protect them trom being deleted or seen
Letter AbbrevIatIon DescrIptIon
r lndicaLes LhaL Lhe ile or direcLory can be read
w lndicaLes LhaL Lhe ile or direcLory can be wriLLen Lo
x lndicaLes LhaL Lhe ile can be execuLed; shell scripLs always have Lhe x per-
mission Lurned on. An x permission or a direcLory indicaLes LhaL you can
Lake a direcLory lisLin o Lhe direcLory Lo see iLs subdirecLories and iles.
- lndicaLes Lhe permission is noL ranLed
1able 2-5 Permissions
56 Chapter 2 UnderstandIng the LInux fIle System
UnderstandIng DIrectory Management Commands 57
by a user. 1here are several hidden tiles that are created by detault vhen a user account
is created. When you use the ls ~l command, you`ll notice a directory named dot (.,
and one named dot dot (..,. 1he single dot represents your current directoryevery
directory has one ot these. 1he tvo dots represent the parent. 1he existence ot a direc-
tory named dot dot is vhy you can issue the cd .. command to navigate to your par-
ent directory.
Next you vill use these tvo options vith the ls command.
1o eecute the ls connand:
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. 1ype ls -l, and then press Lnter. A long listing ot your current
directory appears.
3. Pecord the number ot directories and tiles.
4. Pecord the permissions tor one ot the tiles.
3. 1ype ls -a, and then press Lnter. A listing ot hidden tiles in your current
directory appears.
6. Pecord the number ot hidden tiles.
7. Nov, combine these options on one line.1ype ls -al, and then press Lnter.
A listing ot hidden tiles in your current directory appears as vell as all other
tiles. (1he order ot the options does not matter. So, ls -la vould vork, too.,
8. Pecord the permissions ot just the hidden tiles.
9. 1o exit the 1erminal emulation program, type exit, and then press Lnter.
10. Iog out.
1he QOHMV and VQHMV Commands
1he mkdir command, vhich creates a nev directory, normally returns no output to the
screen. 1he mkdir command takes the tolloving torm
mkdir d1rectory
1he path can be either tull or partial. lor example, to create a directory called paychecks,
you vould execute the tolloving command
mkdir paychecks
Conversely, you use the rmdir command to remove an empty directory. 1he rmdir
command takes the tolloving torm
rmdir d1rectory
2
1he path can be either tull or partial.
When removin a direcLory wiLh Lhe rmdir command, Lhe direcLory musL
be empLy and your currenL direcLory cannoL be Lhe direcLory you are Lryin
Lo remove.
1o remove the paychecks directory just shovn you vould use the rmdir command
rmdir paychecks
Next you vill create a directory named Class, and then remove it.
1o create and renove a directory:
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. 1ype pwd, and then press Lnter.Your current vorking directory is displayed.
3. 1ype mkdir Class, and then press Lnter to create a nev directory
named Class.
4. 1o remove the directory you just created, type rmdir Class, and then
press Lnter.
3. Create the Class directory again using the mkdir command.
6. Navigate to the Class directory, by typing cd Class, and then press Lnter.
7. 1ype pwd, and then press Lnter. Notice that Class directory is your present
vorking directory.
8. 1ype rmdir Class, and then press Lnter. An error message results. ligure 2-9
shovs a result ot attempting to remove your present directory.
9. 1o navigate to the parent directory, type cd .., and press Lnter.
10. 1ype pwd, and then press Lnter.Your current vorking directory is displayed.
Pecord it nov.
11. 1ype rmdir Class, and then press Lnter.You are nov able to remove the
Class directory because it is no longer your current vorking directory.
12. 1o exit the 1erminal emulation program vindov, type exit, and then
press Lnter.
13. Iog out.
8MT
58 Chapter 2 UnderstandIng the LInux fIle System
UsIng dItIng Commands 59
9SING )DI1ING 'OMMANDS
In the Iinux system you use editors to create shell script programs. Lditors are pro-
grams that allov you to create, copy, and remove text vithin a tile. Lditors are similar to
vord-processing sottvare. 1here are several ditterent editors, so you need to try out a
variety ot them in order to determine the one that tits your needs and style best. It is
important that you tamiliarize yourselt vith these programs because you occasionally
need to use them vithin shell script programs.
1able 2-6 lists the most commonly used editor programs.
1he ZM Program
Visual Intertace or vi, as it`s more commonly called, operates in several modes.While the
vi editor is not as user-triendly as some ot the other editors, particularly the graphical
ones, it is the most commonly used editor on most Iinux plattorms. It operates in tvo
dItor Program Purpose
vi Allows you Lo creaLe a new ile; iL is somewhaL more diiculL Lo naviaLe
Lhan mosL raphical word-processin prorams. 1he vi ediLor is Lhe mosL
commonly used ediLor on Linux sysLems.
gedit User-riendly raphical LexL ediLor
1able 2-6 LdiLor prorams
fIgure 2-9 Nessae displays when you aLLempL Lo remove your parenL direcLory
2
modes. Connand node is vhen you input commands, telling the vi editor vhat you
vant to do. 1et node is vhen you type in your text or code. Because you use the key-
board to enter commands and text, the Lscape key allovs you to toggle back and torth
betveen command mode and text mode. It is important to remember that you must issue
one ot the commands listed in 1able 2-7 betore you enter any text.
Command DescrIptIon
I lnserLs or moves Lhe cursor Lo Lhe beinnin o Lhe currenL line and
allows you Lo enLer LexL Lhere
i lnserLs LexL aL Lhe currenL locaLion o Lhe cursor
O Opens or adds a new blank line above Lhe currenL line
o Opens or adds a new blank line below Lhe currenL line
A Appends a new blank line Lo Lhe end o Lhe currenL line
a Appends a new blank line immediaLely aLer Lhe currenL locaLion o
Lhe cursor
R RepresenLs Lhe replace command mode; characLers you Lype replace
currenL characLers sLarLin aL Lhe locaLion o Lhe cursor
r Replaces Lhe characLer aL Lhe locaLion o Lhe cursor
k or UP ARROW Noves up one line
or DOWN ARROW Noves down one line
h or LLF1 ARROW Noves one characLer posiLion Lo Lhe leL
l or RlGH1 ARROW Noves one characLer posiLion Lo Lhe rihL
w Noves Lhe cursor Lo Lhe nexL word
b Noves Lhe cursor Lo Lhe previous word (b or back)
Shift+G Noves Lhe cursor Lo Lhe end o Lhe ile
N ollowed by Noves Lhe cursor Lo Lhe 2Lh line (where 2 represenLs a number) in Lhe
Shift+G ile. For example, 3 ollowed by Shift+G, Lakes you Lo Lhe Lhird line.
D DeleLes LexL rom Lhe currenL cursor posiLion Lo Lhe end o Lhe
currenL line
de or dw DeleLes Lhe currenL word
db DeleLes Lhe previous word (b or back)
d{ DeleLes all Lhe LexL rom Lhe currenL cursor locaLion Lo Lhe beinnin
o Lhe line
d| DeleLes all Lhe LexL rom Lhe currenL cursor locaLion Lo Lhe end
o Lhe line
dh DeleLes Lhe previous leLLer
dl or x DeleLes Lhe currenL leLLer
dd DeleLes Lhe currenL line
dw DeleLes Lhe currenL word
1able 2-7 Common vi commands
60 Chapter 2 UnderstandIng the LInux fIle System
UsIng dItIng Commands 61
You can run the vi editor by simply typing the command vi in the 1erminal emula-
tion vindov.1hen, you can enter your text and save it to a tile. Hovever, vi is normally
executed vith the tile`s path, as in this example
vi payroll
Next you vill use the vi editor to create a tile and manage text and code vithin that tile.
1o use vi to create and nanage a file:
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. 1ype vi file42.txt, and then press Lnter. A screen like the one shovn
in ligure 2-10 appears. 1he vi editor opens the tile named tile42.txt. (Note
that the - symbol is called the tilde.,
3. 1o insert text, press Lsc, and then type i.You are nov in the text mode.
4. Lnter the tolloving text (be sure to press Lnter at the end ot each line,.
Note It you make a mistake vhen typing in the text, you`ll need to use the
Lscape key to toggle back and torth betveen text and command mode. Peter
to the commands in 1able 2-7.
Line 1 of the vi editor.
Line 2 of the vi editor.
Line 3 of the vi editor.
Last line of the vi editor.
3. 1o copy the tirst tvo lines and place them at the end ot the tile, move your
cursor to the tirst character on the tirst line. Press Lsc, type 2, and then type y
tvice. 1his yanks or copies, the tirst tvo lines and places them in the vi butter.
6. Move your cursor to the end ot the tile by pressing Shift+G. 1he cursor
moves to the tirst character on the last line.
7. 1o put or paste the tvo previously yanked lines, type p. Notice that this
places a copy ot the tvo lines at the end ot the tile.
Command DescrIptIon
u Undoes Lhe previous command
yy Yanks, or copies, one line inLo Lhe vi buer; Lhe buer is simply an
area o memory or holdin daLa
p PuLs or pasLes lines previously yanked and residin in Lhe vi buer Lo
a new locaLion
Nyy Yanks, or copies, 2 lines (where 2 represenLs a number) inLo Lhe
vi buer
:wq! WriLes and Lhen quiLs vi
1able 2-7 Common vi commands (conLinued)
2
8. 1o delete the tirst tvo lines, move the cursor to the tirst character on the tirst
line by pressing 1 tolloved by Shift+G.Your cursor moves to the tirst line.
9. Press d tvice to delete the tirst line ot text.
10. Pepeat Step 9 to delete the second line ot text. When complete, the tile
should look like ligure 2-11.
fIgure 2-11 1he ouLpuL o Lhe vi command
fIgure 2-10 1he vi command chanes
62 Chapter 2 UnderstandIng the LInux fIle System
UnderstandIng fIle Management Commands 63
11. 1ype :wg!, and then press Lnter. 1he tile is saved and your prompt is
returned.
12. Close your vindov, and then log out.
9NDRS1ANDING *IL 1ANAGMN1 'OMMANDS
lile management commands help you manipulate tiles.While you use the editor commands
to manipulate tile content, you use tile management commands to manipulate the tiles
themselves such as vhen you create copies ot existing tiles, move or rename existing tiles,
or even merge text trom multiple tiles. It is important to understand these commands
because you vill use them on a daily basis.1hey can also be used in shell scripts.1able 2-8
includes some ot the more commonly used tile management commands.
1he cp Command
1he cp command allovs you to make a copy ot a tile. It takes the general torm
cp ot1onsourcedest1nat1on
1his is vhere source is the source tilethe tile you vant to copy.1he source tile must
exist or the cp command generates an error. 1he dest1nat1on is the tile to vhere
you vant to copy the source data. 1he destination tile does not have to exist. It is user
detined, meaning that the user can change the destination tilename. When you use the
cp command vith the ~i option tor interactive mode, it the destination tile ooes exist,
a message is displayed asking vhether or not you vould like to overvrite the tile.
1he cp Command wIth a full or PartIal Path for oth the Source
and DestInatIon fIlenames
1he cp command accepts any combination ot tull and partial paths tor the source and
destination tiles. Iet`s look at an example. Peter back to ligure 2-1 ot the 1ovnsend
1oyota tree structure. In order to copy the Apr.dat tile trom the Payroll directory to the
cp CreaLes a copy o an exisLin ile
mv Noves or renames an exisLin ile
sort SorLs a ile's ields in eiLher ascendin or descendin order
cut Pulls LexL ouL o a ile; Lhe oriinal LexL wiLhin Lhe ile remains inLacL
paste Neres Lhe LexL rom mulLiple iles
diff Displays Lhe dierences beLween Lwo iles; Lhis is useul or veriyin Lhe inLeriLy o a
ile aainsL a masLer ile
rm Removes a ile
uniq Removes duplicaLe records rom a sorLed ile
1able 2-8 File manaemenL commands
2
1ovnsend1oyotaI1Project3 directory, you can execute the tolloving command
using tull paths
cp /TownsendToyota/Accounting/Payroll/Apr.dat/
TownsendToyota/IT/Proect3/Apr.dat
Once successtully completed, you have a copy ot Apr.dat in both the
1ovnsend1oyotaAccountingPayroll and 1ovnsend1oyotaI1Project3 directories.
In order to copy the leb.dat tile, located in the 1ovnsend1oyotaAccountingPayroll to
another tile called lebbackup.dat vithin the same directory, you vould issue this partial path
cp Feb.dat Febbackup.dat
Once successtully completed, you have tvo tiles the original, leb.dat and the duplicate
copy, lebbackup.dat. Both are in the same directory.
UsIng the cp Command to Copy a fIle to the Parent DIrectory
or a SIblIng DIrectory
In order to copy the May.dat tile to the parent directory, you use a partial path tor the
destination tile as shovn in this example
cp May.dat ../May.dat
Once successtully completed, you have a copy ot May.dat in the parent directory.
In order to copy the un.dat tile, located in the 1ovnsend1oyotaAccountingPayroll
to the sibling directory named 1ovnsend1oyotaAccountingGeneralIedger, you can
use a partial path on the destination as shovn in this example
cp Jun.dat ../GeneralLedger/Jun.dat
Once successtully completed, you have a copy ot un.dat in the 1ovnsend1oyota
AccountingGeneralIedger sibling directory.
1he QZ Command
1he mv command allovs you to move, or rename, a tile or directory. It takes the tol-
loving torm
mv sourcedest1nat1on
As vith the cp command, the source tile must exist.1he destination can be user detined.
While you use Lhe mv command Lo boLh move and rename iles and direcLo-
ries, Lhe Lerm move is used when Lhe source paLh and Lhe desLinaLion paLh
are in dierenL direcLories. 1he Lerm rename is used when Lhe source paLh and
Lhe desLinaLion paLh is in Lhe same direcLory.
8MT
64 Chapter 2 UnderstandIng the LInux fIle System
UnderstandIng fIle Management Commands 65
Iike the cp command, it you use the ~i option vith the mv command, it prompts you
betore it moves a source tile to an existing destination tile.
1he source and destination paths can be either a tull or partial path to a tile or a directory.
Hovever, the source and destination cannot be identicalyou cannot move a tile to itselt.
UsIng the mv Command to Rename a fIle or Move a fIle to
Another DIrectory
1o rename a tile, consider the tolloving example vhere a tile called x.tile is changed to
the nev name y.tile.1he contents ot the nevly changed tilename remain the same. Because
you are renaming and not copying, the original tile named x.tile no longer exists.
mv x.file y.file
You can also use the mv command to change the location ot the tile. As in the previ-
ous example, the contents remain the same, but the tile is moved and has a nev name.
1hink ot the move as it you vere physically moving something trom one place to
another. Its location changes but the contents do not. In the tolloving example, the
x2.tile is moved to the dirA directory and renamed y2.tile.
mv x2.file /dirA/y2.file
UsIng the mv Command When the Source and DestInatIon Have
the Same Name
1he only time the source and destination tile can have the same name is vhen you are
moving it to another directory. As previously noted, you cannot rename a tile to its same
name.Yet, in this example, mv /dirB/x2.file /dirA/x2.file, the actual tilename
stays the samex2.tile. 1his is because the directory name ot the source, dirB, and the
directory name ot the destination, dirA, are ditterent.1his results in tvo completely dit-
terent paths, hence tvo completely ditterent tilenames as tar as Iinux is concerned.
Next you vill use the cp and mv commands to become tamiliar vith hov they vork.
1o copy and nove files:
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. 1ype mkdir dirA1, and then press Lnter.
3. lirst, you need to create a tile to duplicate. Lse vi to create a tile
named f1.dat.
4. 1ype cp f1.dat f8.dat, and then press Lnter to copy the tile you created
in the previous step.
3. 1ype ls, and then press Lnter. Notice that the listing ot tiles includes the tile
you just created as vell as the copy ot that tile.
2
6. 1ype cp -i f1.dat f8.dat, and then press Lnter. 1he command
interactively prompts you asking it you vant to overvrite the tile.
7. 1ype y, and then press Lnter.
8. 1ype mv f1.dat f9.dat, and then press Lnter. 1he t1.dat tile is moved
to t9.dat.
9. 1ype mv -i f8.dat f9.dat, and then press Lnter. 1he command interac-
tively prompts you, asking it you vant to overvrite the tile.
10. 1ype y, and then press Lnter.
11. 1ype ls, and then press Lnter. Notice that the t9.dat tile no longer exists,
but the t1.dat tile does. Nov look at ligure 2-12, it shovs the commands as
you`ve used them in this exercise.You can see a listing displaying the tiles in
the directory, in this case dirA1, betore they are copied or moved.You can
also see the message generated trom the ~i option vhen it is used vith the
cp and mv commands.
12. 1o exit the 1erminal emulation program, type exit, and then press Lnter.
1he WSVX Command
1he sort command is used to sort data either in ascending or descending order. lor
example, it you vant to alphabetically sort a tile containing employee names, you use
fIgure 2-12 1he ouLpuL o Lhe cp and mv commands
66 Chapter 2 UnderstandIng the LInux fIle System
UnderstandIng fIle Management Commands 67
this command. Or, it you vant to sort a numeric tield in descending order, you also use
the sort command. 1he basic syntax ot the sort command is
sort f11ename
In order to run the sort command tor a tile named unsort.dat, you enter the tolloving
command
sort unsort.dat
When you use the sort command, the detault is tor the output to be displayed on your
screen. Hovever, you can redirect the output to a tile by using the greater-than opera-
tor, >. 1he tolloving example sorts a tile named unsort.dat and places the output to a
nev tile named sort.dat.1he original tile remains intact.1here is no output to the screen
because it is being redirected to a tile. 1he name ot the tile tolloving the greater-than
symbol is user detined.
sort unsort.dat > sort.dat
By detault, the sort command sorts in ascending order, or lover to higher.You can sort
in descending order, called reverse order, using the ~r option as in this command
sort ~r f11ename
1he GYX Command
1he cut command allovs you to strip text out ot tiles and display the cut text on the screen
or redirect the text to another tile. 1his command is most otten used to cut tields vithin a
tile.1he data is not permanently cut trom the tile.1he command does not alter the original
tile and it automatically opens the tile tor you.1he basic syntax tor the cut command is
cut ot1onsf11ename
You need to be avare ot tvo important options. 1he ~d option is used to identity the
delimiter in the tile. 1he colon is generally used as a separator or deliniter betveen
tields, letting programs knov vhere one tield begins and one ends. lor example, ~d:
identities the colon as a delimiter.1he ~f option is used to identity vhich tield you vant
based on the delimiter. lor example, consider the tolloving record tor an animal clinic
l00l:King Pup:Dog
1he tirst tield,1001, represents the ID, the second tield,King Pup, represents the ani-
mal`s name, and the third tield, Dog, represents the type ot animal. Colons are used to
delimit the tields in this example.You use a colon, or some other character, instead ot a
space to separate tields.1he space can not be used because it may actually separate vords
in a tield, such as King Pup.
Assuming the tile is named animal.dat, the command to display the tirst tield is
cut ~d: ~fl animal.dat.1he command to display the tirst and third tields vould be
cut ~d: ~fl,3 animal.dat.
2
Next you vill create a tile vith several employee records in it. Lach record vill consist
ot tvo tieldsan employee number tolloved by a colon and the employee name.
1o use the cut connand in a file:
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a tile named unsort.dat using the vi editor.
3. Lnter the data in tvo tields. Note in the data belov, that the tormat is
num|er.name vhere num|er represents the tirst tield and name represents the
second tield. 1he colon (, is the delimiter. Place the tolloving data in the tile
noting that there are duplicate 3:Jessie records. (You vill use these tvo
records later vhen you learn about the uniq command., Atter you enter the
data make sure you press Lnter at the end ot each line, save the tile, and then
exit the vi editor.
3:Jessie James Garcia
3:Jessie James Garcia
2:Zachary Scott Pheng
4:Lorenzo Todd Von Schloss
1:Micki McSunday-Washington
4. 1o cut the tirst tield, type cut -d: -f1 unsort.dat, and then press
Lnter. See ligure 2-13, the tirst tield appears on your screen, but the data has
not been removed trom the original tile.
3. 1o cut the second tield, the names, and then send the output to a tile named
name.dat, type cut -d: -f2 unsort.dat > name.dat, and then press
Lnter. See ligure 2-13.
6. 1o display the contents ot the nev tile, type cat name.dat, and then press
Lnter. See ligure 2-13, notice that the nev tile only has the names in it.
7. 1o ensure that the original contents ot unsortcut.dat have not been literally cut,
type cat unsort.dat, and then press Lnter.1he original contents that vere
created in Step 3 appear unchanged on your screen as shovn in ligure 2-13.
8. 1o exit, type exit, and then press Lnter.
9. Iog out.
68 Chapter 2 UnderstandIng the LInux fIle System
UnderstandIng fIle Management Commands 69
1he TEWXI Command
Whereas the cut command cuts tile tields, the paste command pastes, or merges, data
trom one tile to another. 1he data can then be merged into a nev tile.1he basic syntax
ot the paste command is
paste f11ename_onef11ename_two
1he above code merges each line trom tile tvo vith each line ot tile one. lor example,
assume you had tvo tiles each containing name data. 1he last.dat tile contents are
Smith Jones Adams, and the tirst.dat tile contents are Joe Mary Sue. It you enter the
command paste first.dat last.dat, then your output to the screen vould be
Joe Smith
Mary Jones
Sue Adams
It you had entered the command paste last.dat first.dat, then your output
vould be
Smith Joe
Jones Mary
Adams Sue
1he contents ot the original tiles remain the same.You can also create an altogether nev
tile using the redirect output (>, symbol. It you enter the command
paste first.dat last.dat > first_last.dat, you vould create a nev tile
called tirst_last.dat vith the pasted data trom the tirst.dat and last.dat tiles.
fIgure 2-13 DemonsLraLin Lhe cut command
1he oriinal ile's conLenLs
1he oriinal ile's conLenLs
unchaned
1he second ield cuL and
placed in anoLher ile;
noLice Lhe new ile only
has names in iL
1he irsL ield cuL rom Lhe
ile is noL acLually removed
2
Suppose that Mama`s Hardvare Store maintains tvo separate tiles. One tile is called product
and contains the names ot top selling sale items, and the other tile is called quantity and con-
tains the amount ot the sales items that have been ordered.1he ovners vould like the intor-
mation to appear in one tile named orders.1o do that, you need to paste these tiles together.
ligure 2-14 shovs the contents ot the tvo original tiles as vell as the use ot the paste com-
mand to merge these tiles and redirect the contents to the nev tile.
1he VQ Command
1he rm command is used to remove a tile permanently trom the tile system tree hier-
archy. 1here is no vay to recover a removed tile. 1he basic syntax ot the command is
rm f11ename
In the tolloving example, the tile named resume.dat is removed.
rm resume.dat
Some versions o Linux ask you Lo veriy LhaL you really wanL Lo remove a ile
beore iL is removed. OLher versions simply remove Lhe ile wiLhouL askin.
Use cauLion and consider LesLin Lhis concepL by removin a LesL ile beore
removin any iles rom your ile hierarchy.
fIgure 2-14 1he paste command or Nama's Hardware SLore
ConLenLs o quanLiLy ile
ConLenLs o orders ile
usin paste
DeaulL display o merin
quanLiLy and producL iles
usin paste
ConLenLs o producL ile
70 Chapter 2 UnderstandIng the LInux fIle System
UnderstandIng fIle Management Commands 71
1he YRMU Command
1he uniq command is to used to tind duplicate lines trom a sorted tile. 1his is a partic-
ularly helptul programming technique to use it redundant records happen to exist in a tile.
1he uniq command does not remove the duplicate lines, it just displays them on the
screen.1he uniq command opens the tile tor you. 1he basic syntax ot this command is
uniq f11ename
1he output detaults to the screen, displaying the duplicates. You can also redirect the
output to a user-detined tilename using the tolloving command
uniq duplicates.dat > uniq.dat
In this case, the repeating lines trom the duplicates.dat tile are redirected to the uniq.dat
tile.You use redirection vhen you vant to reter to the original data tile. In this case, you
vould process the uniq.dat tile because any redundant records have already been
removed trom the tile.
1he uniq command has a usetul option tor counting the number ot occurrences ot a line
in a tile. 1his is helptul vhen you vant to identity the number ot duplicates you have in
a tile.1he tolloving uniq command vith the attached ~c option accomplishes this
uniq ~c duplicates.dat
Next you vill use the uniq command to remove duplicate items trom a grocery list
vhere several people in the household have added redundant items.
1o use the unig connand to renove duplicates fron a file:
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a tile named grocery.dat using the vi editor.
3. Lnter the tolloving data. As you enter the data, make sure you press Lnter at
the end ot each line. Save the tile, and then exit the vi editor.
soup
soup
pizza
turkey
lettuce
lettuce
lettuce
apples
bananas
grapes
grapes
2
4. 1o remove the duplicate grocery items, type unig grocery.dat, and then
press Lnter. See ligure 2-13.
3. 1o redirect this to a tile that you can take to the grocery store, type
unig grocery.dat > list.dat, and then press Lnter.
6. 1o display the contents ot the nev list, type cat list.dat, and then press
Lnter. See ligure 2-13. Notice that nov the items are part ot the list.dat tile.
7. 1o exit, type exit, and then press Lnter.
8. Iog out.
fIgure 2-15 OuLpuL o Lhe uniq command
SLep 6
SLep 4 resulLs o
uniq command
72 Chapter 2 UnderstandIng the LInux fIle System
RevIew QuestIons 73
'HAP1R 7UMMARY
1he Iinux tile system is designed tor storage and quick access. Directories contain
other directories or tiles. liles contain only data. 1he Iinux tile system is hierarchi-
cal, or treelike, in nature. In the Iinux tile system, the root directory (, is the top
ot the tree. All tiles and tolders branch trom the root directory. 1he system directo-
ries are created during the installation ot the Iinux operating system, and they
should not be moditied or deleted.
When navigating the tree hierarchy, you need to be avare ot vhere you are, or
vhat your current directory is. With the hierarchy structure, there is a parent-child
relationship. 1he parent directory is reterred to as dot dot ( .. ,. A child directory
is reterred to by name. Siblings have the same parent. A tull path begins at the root
directory. A partial path does not include the root directory.
Directory management commands deal vith manipulating and displaying the direc-
tories in the tree. 1he most commonly used commands are cd tor changing the
current directory location, pwd tor displaying the current directory location, and ls
tor displaying the contents ot a directory.
Lditors and editor commands allov you to manipulate the contents in a tile.1he most
commonly used editor is vi. It can be used to add, copy, delete, insert, or modity data
vithin a tile.
1he tile management commands allov you to manipulate the actual tiles vithin the
tree. 1he cp command is used tor copying an existing tile to another tile, creating
tvo tiles. 1he mv command is used tor moving or renaming an existing tile, hov-
ever, you end up vith just one tile vhen you use this command. 1he rm is used to
remove a tile.
6VIW 5US1IONS
1. Lse the command to change directory locations.
a. cd
b. rm
c. mkdir
d. cut
2. Which ot the tolloving are considered tull paths (Choose all that apply.,
a. dirA
b. ..dir2
c. payroll
d.
2
3. Lse the command to delete a directory.
a. delete_dir
b. mkdir
c. rmdir
d. cat
4. Which ot the tolloving are considered partial paths (Choose all that apply.,
a. dirA
b. ..dir2
c. payroll
d.
3. Which ot the tolloving are text editors (Choose all that apply.,
a. vi
b. emacs
c. ls
d. cat
6. 1he command sorts data in descending order.
a. sort ~r
b. sort
c. mkdir
d. reverse
7. 1o change the vorking directory location to a sibling directory named dir2, you
enter the command.
a. cd /
b. cd \
c. cd ..\dir2
d. cd ../dir2
8. 1he directory holds mounted drives.
a. root
b. boot
c. mnt
d. var
74 Chapter 2 UnderstandIng the LInux fIle System
RevIew QuestIons 75
9. 1he tile system holds tiles and directories that vary in size.
a. root
b. boot
c. mnt
d. var
10. 1he command creates a directory named vinchester in the
root directory.
a. mkdir /winchester
b. mkdir ../winchester
c. mkdir \winchester
d. md /winchester
11. 1he option tor the ls command displays a long listing.
a. ~i
b. ~a
c. ~l
d. ~c
12. Which ot the tolloving represents your parent directory
a. ..
b. .
c.
d.
13. 1he command allovs you to change directory locations to a
child directory named child1.
a. mkdir childl
b. cd ../childl
c. cd childl
d. cd /
14. In vi, the command to change to insert mode is
a. o
b. O
c. i
d. d
2
13. 1he command deletes a tile.
a. rmdir
b. cd
c. rm
d. pwd
16. 1he command displays your present vorking directory.
a. cat
b. cd
c. touch
d. pwd
17. 1he system directory contains the Iinux kernel.
a. boot
b. root
c. dev
d. var
18. 1he in the vi editor allovs you to save and quit the program.
a. :wq
b. q!
c. w!
d. !
19. 1he command to rename a tile is .
a. mv
b. cp
c. del
d. rename
20. 1he command makes a duplicate ot a tile.
a. mv
b. cp
c. del
d. rename
76 Chapter 2 UnderstandIng the LInux fIle System
Hands-on Projects 77
,ANDSON 4ROJC1S
Project 2-1
In this project, you vill compare your ovn tamily tree to the Iinux tile system. Pesearch
your tamily tree no turther than your grandparents. Drav your tamily tree on a separate
piece ot paper, and then explain hov your tamily tree compares to vhat you`ve learned
about the Iinux tile system in this chapter.
Project 2-2
In this project, you vill compare a building`s evacuation plan tor one room to the use
ot paths in the Iinux tile system.You vill tirst need to get a copy ot a building evacua-
tion plan tor one room trom your local church, school, or vork. 1hen, vrite a descrip-
tion ot hov the evacuation plan relates to a path in the Iinux tile system hierarchy.
Project 2-3
In this project, you vill execute various commands in your home directory.
1. Iog in to the Iinux computer as a user, and then open a 1erminal emulation vindov.
2. 1ype touch file1.dat, and then press Lnter.
3. Pepeat Step 2 three additional times, hovever, change the number at the end ot
the tilename each time, e.g., tile2.dat, tile3.dat, tile4.dat.
4. Create a hidden tile by typing touch .hiddenfile.txt, and then press Lnter.
3. Issue a long listing ot all the tiles in the directory by typing ls -al, and then
press Lnter.
6. On a separate sheet ot paper, label and identity each column that is displayed.
7. Close your vindov, and then log ott.
Project 2-4
In this project, you vill search the Ped Hat Web site tor intormation on various Iinux
commands in order to learn hov to use the Web site as a research tool. You vill need
access to the Internet.
1. Open a Web brovser.
2. In the Address or location box on your brovser, type hiip//uuu.rehai.com, and
then press Lnter. 1he Ped Hat Web site appears.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
2
3. In the Search Ped Hat text box, type ls, and then click the Go button. 1he
screen displays a listing ot the links to documents related to the ls command.
4. Click one ot the documents and reviev it. Keep checking documents until you
locate one that gives you additional insight into the ls command.
3. Based on your tindings at this Web site, identity something nev you`ve learned
about the ls command.
6. Pepeat Steps 3 through 3 tor the pwd command.
7. Pepeat Steps 3 through 3 tor the cp command.
8. Pepeat Steps 3 through 3 tor the vi editor.
9. Close your Web brovser.
Project 2-5
In this project, you vill execute commands, and then drav the resulting tree structure.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1ype mkdir Project2-5, and then press Lnter.
3. 1ype cd Project2-5, and then press Lnter.
4. 1ype mkdir R, and then press Lnter.
3. 1ype mkdir S, and then press Lnter.
6. 1ype mkdir T, and then press Lnter.
7. 1ype cd T, and then press Lnter.
8. 1ype touch t1.dat, and then press Lnter.
9. 1ype touch t2.dat, and then press Lnter.
10. 1ype touch t3.dat, and then press Lnter.
11. 1ype cd ../R, and then press Lnter.
12. 1ype touch r1.dat, and then press Lnter.
13. 1ype touch r2.dat, and then press Lnter.
14. 1ype cd ../S, and then press Lnter.
13. 1ype touch s1.dat, and then press Lnter.
16. 1ype touch s2.dat, and then press Lnter.
17. 1ype cd .., and then press Lnter.
18. Drav the resulting tree structure.
19. Close your vindov, and then log out.
,ERHWSR
4VSNIGX
78 Chapter 2 UnderstandIng the LInux fIle System
Hands-on Projects 79
Project 2-6
In this project, you vill create a directory tree based on the output ot the tree com-
mand shovn in ligure 2-16.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create the directory tree shovn in ligure 2-16.You need to use these commands
to complete this project cd, pwd, mkdir, and rmdir.
3. Pecord the order in vhich you used each command to create the tree.
4. Close your vindov, and then log out.
Project 2-7
In this project, you vill create the directory shovn in ligure 2-17 in order to reintorce
your understanding ot the Iinux tile system hierarchy.You vill need to use these com-
mands to complete this project cd, pwd, mkdir, and rmdir. linally, record the com-
mands in the order in vhich you used them to create the tree.
,ERHWSR
4VSNIGX
fIgure 2-16 1ree you will creaLe or ProjecL 2-6
,ERHWSR
4VSNIGX
2
Project 2-8
In this project, you vill use the tree structure trom Project 2-3 to manipulate the tiles
and directories created. Project 2-8 requires completion ot Project 2-3.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1ype cd Project2-5, and then press Lnter.
3. 1ype cd T, and then press Lnter.
4. 1ype ls, press Lnter, and then record the output.
3. 1ype cp t1.dat t11.dat, and then press Lnter.
6. 1ype cp t2.dat t22.dat, and then press Lnter.
7. 1ype ls, press Lnter, and then record the output.
8. 1ype mv t3.dat t33.dat, and then press Lnter.
9. 1ype ls, press Lnter, and then record the output.
10. Pecord the ditterence betveen the cp and mv commands.
11. 1ype cd ../S, and then press Lnter.
12. 1ype ls, press Lnter, and then record the output.
13. 1ype cp s1.dat ../R/r5.dat, press Lnter, and then record vhat this com-
mand does.
14. 1ype cd ../R, and then press Lnter.
13. 1ype ls, press Lnter, and then record the output.
16. Close your vindov, and then log out.
,ERHWSR
4VSNIGX
$HONL
waLer Lrees
oceans seas
aLl.daL pac.daL Red.daL
Oak.daL Pine.daL
8lack.daL
.birds.daL
fIgure 2-17 1ree you will creaLe or ProjecL 2-7
80 Chapter 2 UnderstandIng the LInux fIle System
Hands-on Projects 81
Project 2-9
In this project, you vill use vi to create a data tile vith records.You vill then sort the data.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1ype mkdir Project2-9, and then press Lnter.
3. 1ype cd Project2-9, and then press Lnter.
4. 1ype vi infile.dat, and then press Lnter. 1he vi editor opens.
3. 1o insert text, press Lsc, and then type i.
6. Lnter the tolloving text and make sure you press Lnter at the end ot each line.
(Lach rov is considered an employee record vith colons separating the tields. 1he
tirst tield is the employee number. 1he second tield is the employee name, and the
third tield is the employee salary.,
401:Sue Fanglee Tuen:$34000
104:Sammy Jones:$55402
207:Tammy Phang:$50040
214:Zoe Buhari-Jones:$56000
505:James Brongan:$50500
7. 1o save the tile, press Lsc, and then type the colon symbol (:,. 1he cursor moves
to the bottom ot the screen vith a colon to its lett.
8. 1o vrite the tile, type wg!, and then press Lnter. 1he prompt returns.
9. Sort the data in ascending order by typing sort infile.dat, press Lnter, and
then record the output.
10. Sort the data in descending order by typing sort -r infile.dat, press
Lnter, and then record the output.
11. Sort the data in descending order and redirect the output to another tile by typing
sort -r infile.dat > reverse_sort.dat, and then press Lnter.
12. Sort the data in ascending order, redirect the output to another tile, and then
record the command you used.
13. Close your vindov, and then log out.
Project 2-10
In this project, you vill use the tiles created in Project 2-9. Project 2-10 requires com-
pletion ot Project 2-9.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1ype cd Project2-9, and then press Lnter.
3. Cut the tirst tield.
4. Cut the second tield.
3. Cut the third tield.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
2
6. Cut both the tirst and third tield and redirect the output to a nev tile named
salary.dat.
7. Make a duplicate ot intile.dat by typing cp infile.dat infile2.dat, and
then press Lnter.
8. Open the tile named infile2.dat, and add tive additional records. Add a sixth
record that has your name. Also, create a tictitious employee number and
employee salary to complete your record.
9. 1ype diff infile.dat infile2.dat, and then press Lnter. Pecord the output.
10. Close your vindov, and then log out.
'AS 4ROJC1S
Case 2-1
You have been hired by 1MI to design an application using shell script programs. 1MI
needs you to design and create a nev directory structure.
1he company has several departments accounting, sales, manutacturing, intormation tech-
nology, and headquarters. 1he accounting department has accounts receivable, accounts
payable, and payroll tunctions vithin it. 1he manutacturing department runs three shitts
and a veekend shitt.1he intormation technology department has tive projects in progress.
1he sales department has ottices located in the West, Last, North, and South.
lirst, design the Iinux tile system hierarchy on paper. Keep in mind that the depart-
ments, tunctions, shitts, regions, and projects need to translate into directories. Next, you
need to create this hierarchy on the Iinux system. Create at least one empty tile in each
directory. Lse the department, tunction, shitt, region, or project name as the tilename
and include an extension ot .dat.
Case 2-2
Zonka Corp. has sales ottices in tive countries the Lnited States, Canada, Spain,
Singapore, and lrance. Design your directory structure on paper and then implement it.
Make sure that each country is represented by a directory. Next, create tvo tiles in each
directory named tirst.dat and last.dat.1hese vill be used to hold employees` names vith
an employee`s tirst and last names split betveen tvo tiles. In the tile named tirst.dat, add
the tirst name ot tive employees. In the tile named last.dat, add the corresponding last
name ot the same tive employees.1hen, using the paste command, merge the tirst tvo
tiles together into a nev tile. lor each employee, the nev tile must have the tirst name
tolloved by the last name on one line. 1hen, merge the tirst tvo tiles into another tile.
lor each employee, this tile must have the last name tolloved by the tirst name on one
line. linally, make backup copies ot the nevly merged tiles.
'EWI
4VSNIGXW
'EWI
4VSNIGXW
82 Chapter 2 UnderstandIng the LInux fIle System
83
',%48)6

7,)00 &%7-'7
-RXLMWGLETXIV]SY[MPP
9RHIVWXERHXLIWLIPPPSKMRERHPSKSYXJMPIW
0IEVREFSYXWLIPPZEVMEFPIW
&IGSQIJEQMPMEV[MXLXLIWLIPPIRZMVSRQIRX
0IEVREFSYXWLIPPFYMPXMRGSQQERHW
0IEVREFSYXWLIPPKVEQQEV
9RHIVWXERHGSQQERHX]TIW
8
he Iinux shell is the program that acts as the intertace betveen you and
the operating system kernel. 1he shell accepts input in the torm ot your
commands, and then gives the commands over to the processor tor execu-
tion. You see evidence ot the shell vhen you log in and go to a command
prompt. In this chapter, you vill learn hov the shell is executed and under-
stand the purpose ot the shell and shell grammar. Pedirection vill also be
discussed.
9NDRS1ANDING 1H 7HLL 0OGIN AND 0OGOU1 *ILS
When you log in, a shell is executed and provides you vith a shell prompt. You type
your commands to the right ot the prompt. lrom your previous experience, you knov
that you need a username to log in and interact vith the operating system. Hovever,
vhen a user account is created, it is given a detault shell, vhich is vhat allovs you to
access the operating system. lor Ped Hat Iinux, the detault shell is bash.
As you know rom ChapLer 1, Lhere are several dierenL shells. 1his book
ocuses on Lhe bash shell.
1he bash shell is an Institute ot Llectrical and Llectronic Lngineers (ILLL, Portable
Operating Systems Intertace standard (POSIX, developed by the lree Sottvare
loundation. 1his means it is a standard that comes tree vith the operating system.
1he /etc/profIle ScrIpt fIle
1here are startup tiles in the Iinux directory hierarchy, vhich are used to set up detault
settings tor the user`s environment. 1he startup tiles are read and executed in a specitic
order as the user logs in. 1he logout tile is read and executed as the user logs out.
1he shell reads and executes commands in the etcprotile tile, it it is present. ligure 3-1
shovs vhat`s included in this tile. 1his tile is actually a script. It is important because it is
executed tor every user. Hovever, your tile content may ditter. It you vanted all users to
have a script execute vhen they log in or it you vanted to display a message that all vould
see as they log in, you vould modity this tile accordingly. You typically place any state-
ments at the end ot this tile so you von`t intertere vith other statements already contained
vithin it.1he permissions on this tile are read and vrite tor the root user and read tor all
other users, theretore, you must be logged in as root to modity this tile. Lsers cannot mod-
ity it. Although you may not understand all the code at this point, it vill become clear as
you vork your vay through this book.
Iet`s look at a statement in the etcprotile script to give you an idea ot vhat happens
vith this script. Pecall trom Chapter 1 that the history command allovs you to keep
up to 1,000 commands. It you look at ligure 3-1, you notice a HISTSIZE=l000 state-
ment.1his sets the number ot commands that the history command keeps to 1,000. As
root user, you could change it to 10,000 or even just 100. It you increase it, you keep more
commands in the history list. 1his is helptul because you can see previous commands in
cases vhere you vant to verity the exact syntax ot a command. Hovever, it you increase
the size ot this tile, the tile that keeps the history list, called -.bash_history, vill also
increase over time. 1his means you vill use more disk space tor the enlarged history list.
8MT
84 Chapter 3 Shell asIcs
UnderstandIng the Shell LogIn and Logout fIles 85
You can also see that a variable called $LOGNAME is set in this tile. 1he $LOGNAME
equates to the user account ot the user that is currently logged in. As a System
Administrator you might use this intormation tor auditing purposes.
1he ~/.bash_profIle ScrIpt fIle
Atter the shell executes the etcprotile script tile tor all users, another script executes, it
is called -.bash_protile. Hovever, this tile, in each user`s home directory, is hidden (notice
the dot prior to the tilename,. 1he tile is hidden so you von`t accidentally delete it. 1he
permissions tor this tile are read and vrite tor the ovner and read tor all other users, that
vay each user can customize this tile. ligure 3-2 shovs vhat`s included in this tile. Again,
your content may vary. 1his tile exists so that users can customize their ovn login
processes.1hey can modity this script and place their ovn commands in the tile. lor exam-
ple, it a user vants to display a calendar or the date on the screen each time he or she logs
in, it can be done by changing this tile.1his script tile also adds the directory $HOME/bin
to the PATH so that users can execute their ovn scripts vithout entering a tull path.
# /etc/profile
# System wide environment and startup programs
# Functions and aliases go in /etc/bashrc
if ! echo $PATH ] /bin/grep ~q "/usr/X11R6/bin" , then
PATH="$PATH:/usr/X11R6/bin"
fi
ulimit ~S ~c 1000000 > /dev/null 2>&1
if `id ~gn` = `id ~un` ~a `id ~u` ~gt 14 , then
umask 002
else
umask 022
fi
USER=`id ~un`
LOGNAME=$USER
MAIL="/var/spool/mail/$USER"
HOSTNAME=`/bin/hostname`
HISTSIzE=1000
REPLY="Y"
if ~z "$INPUTRC" ~a ! ~f "$HOME/.inputrc" , then
INPUTRC=/etc/inputrc
fi
export PATH USER LOGNAME MAIL HOSTNAME HISTSIzE INPUTRC REPLY
fIgure 3-1 1he /eLc/proile scripL ile
3
1he Lilde, -, is used Lo represenL Lhe user's home direcLory. 1he - symbol and
$HOME are equivalenL. 1hus ~/.bash_proile is a hidden ile in each user's
home direcLory.
Next you vill modity and test the -.bash_protile tile to become more tamiliar vith its
operation.
1o nodify and test the -/.bash_profile file:
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. 1ype vi .bash_profile, and then press Lnter. 1he shell script is dis-
played on the screen.You don`t need to include the tilde tor your home
directory because vhen you log in, your position in the Iinux tree already is
your ovn home directory.
3. Press Shift+G.Your cursor moves to the bottom ot the screen.
4. 1ype o to open a line ot text in vi.
3. 1ype echo "Hello", and then press Lnter.
6. Save the tile, and then close the editor.
7. In order to test .bash_protile, type bash .bash_profile, and then press
Lnter. 1he text Hello appears on the screen.
8. 1o exit the 1erminal emulation program, type exit, and then press Lnter.
9. Iog out.
# .bash_profile
# Get the aliases and functions
if ~f -/.bashrc , then
. -/.bashrc
fi
# User specific environment and startup programs
PATH=$PATH:$HOME/bin
BASH_ENv=$HOME/.bashrc
export BASH_ENv PATH
unset USERNAME
fIgure 3-2 1he ~/.bash_proile scripL ile
8MT
86 Chapter 3 Shell asIcs
UnderstandIng the Shell LogIn and Logout fIles 87
1he ~/.bash_proile execuLes anoLher hidden ile, called ~/.bashrc, i iL exisLs
on Lhe sysLem. 1he ~/.bashrc scripL in Lurn execuLes anoLher scripL LhaL seLs
your prompL; iL is called /eLc/bashrc and can only be modiied by Lhe rooL
user. Remember LhaL Lhe ~/.bashrc is able Lo be chaned by Lhe user, buL LhaL
Lhe /eLc/bashrc ile can only be chaned by Lhe rooL user.
1he ~/.bash_logout ScrIpt fIle
1here is another hidden tile located in each user`s home directory, vhich is read and
executed each time a user logs out ot the Iinux system, it is named .bash_logout. A prac-
tical use ot the -.bash_logout tile is to check vhen a user logs ott by redirecting the
output ot the date command to a tile. 1hen, you can determine exactly vhen a user
logged ott the system.
Next you vill pertorm an exercise vhere you change the -.bash_logout tile, and then
test it. 1he goal ot this exercise is to have you modity the tile to understand vhat hap-
pens vhen you change it.
1o nodify and test the -/.bash_logout file:
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. 1ype vi .bash_logout, and then press Lnter. 1he shell script is displayed
on the screen.
3. Press Shift+G.Your cursor moves to the bottom ot the screen.
4. 1ype o to open a line ot text in vi.
3. 1o ensure that you are properly logging out, you can add a closing response
by typing echo "Good Bye!", and then press Lnter.
6. Save the tile, and then close the editor.
7. In order to test the .bash_logout tile, type bash .bash_logout, and then
press Lnter. 1he text Good Bye' appears on the screen.
8. 1o exit the 1erminal emulation program, type exit, and then press Lnter.
9. Iog out.
AnoLher way Lo invoke Lhe shell is by enLerin bash aL Lhe command prompL.
lL is locaLed in Lhe /bin direcLory.
8MT
8MT
3
0ARNING AOU1 7HLL :ARIALS
A shell variable is a keyvord that is set by the shell tor a specitic use. It is typically
entered in all uppercase letters.1his is ditterent trom most commands, vhich are entered
in lovercase. Lach shell variable is used tor a ditterent purpose. Notice some ot the shell
variables, such as PATH and HOSTNAME in ligures 3-1 and 3-2.
You can display the contents ot an individual variable by using the echo command and
placing a dollar sign (s, prior to the variable`s name. lor example echo $HOME displays
the home directory. Note that echo - also displays the home directory.
A tev ot the shell variables are listed in 1able 3-1. You can reter to the man pages on
bash tor others.
Next you vill display the contents ot a tev shell variables so you can understand hov to
access them in case you need to retrieve them either at the shell prompt or in a shell script.
1o display the contents of shell variables:
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
Shell VarIable DescrIptIon
PWD 1he mosL recenL currenL workin direcLory seL wiLh Lhe cd command
OLDPWD 1he previous workin direcLory seL by Lhe cd command
BASH 1he ull paLh name used Lo invoke Lhe bash shell
RANDOM GeneraLes a random inLeer beLween 0 and 32,767
HOSTNAME 1he currenL hosLname o Lhe sysLem runnin Linux
IFS lFS or lnLernal Field SeparaLor, used as a separaLor beLween words in Lhe
shell or shell scripLs
PATH ConLains a lisL o direcLories LhaL are used Lo search or commands wiLhin
Lhe Linux Lree hierarchy
HOME 1he home direcLory o Lhe currenL user. Lach user has a home direcLory
when his or her accounL is creaLed. 1his is Lhe deaulL locaLion or sLorin
iles and direcLories or a user.
PS1 RepresenLs Lhe prompL
PS3 RepresenLs Lhe prompL or Lhe select sLaLemenL
TMOUT RepresenLs Lhe amounL o Lime Lhe shell waiLs, wiLhouL user inpuL, beore
exiLin Lhe currenL shell; TMOUT means Lo "LimeouL" Lhe user's session
aLer a speciic amounL o Lime passes
1able 3-1 Some o Lhe imporLanL shell variables
88 Chapter 3 Shell asIcs
LearnIng about Shell VarIables 89
2. 1ype echo $PWD, and then press Lnter. 1he current vorking directory is
displayed. See ligure 3-3.
3. 1ype echo $BASH, and then press Lnter. 1he tull path ot the detault shell,
bash, is displayed. See ligure 3-3.
4. 1ype echo $RANDOM, and then press Lnter. A random number is displayed on
the screen. See ligure 3-3, notice that the number is 22,178.You might use the
RANDOM shell variable in a program that creates random passvords tor users.
3. 1ype echo $PATH, and then press Lnter. 1he command search path is dis-
played on the screen. See ligure 3-3. Here the path is quite long and includes
many directories.
6. 1o exit the 1erminal emulation program, type exit, and then press Lnter.
7. Iog out.
1he conLenLs o a variable seL in Lhe ~/.bash_proile ile override Lhe conLenLs
o a variable in Lhe /eLc/proile scripL ile.
8MT
fIgure 3-3 ConLenLs o a ew shell variables
3
&COMING *AMILIAR WI1H 1H 7HLL )NVIRONMN1
When you enter a command using a partial path, such as cp, hov does the shell knov
hov to execute it When a partial path is used vhen executing a command, the shell
looks at the contents ot the PATH variable until it tinds the directory in vhich the com-
mand is located. Iook again at ligure 3-3 and you see the contents ot the PATH shell
variable tor the user toddm. Notice that a delimiter, in this case a colon, separates each
ot the directories in the path listing. When searching tor the directory that a command
is in, the shell searches each directory, separated by the delimiter in the path list starting
trom lett and moving to the right. It the directory vhere the command is located is
tound in the PATH variable, the command is executed trom that directory. Othervise,
the shell generates an error message indicating the command could not be tound.
When executing a command using its tull path, such as /bin/cp, the shell does not
reter to the PATH contents. Instead it goes directly to the command using the specitied
path. lor the command /bin/cp, the shell moves directly to the /bin directory, vhich
is one ot the system directories that you learned about in Chapter 2.
1he fIle System HIerarchy Standard
Ped Hat supports the File Systen Hierarchy Standard, vhich has been developed
to standardize some ot the system directories on computers running the Iinux operat-
ing system. One important aspect ot the standard is to use the usrlocalbin directory
to store all ot your shell scripts that need to be available to many users. Note that only
the root user can place scripts here, but all others can read and execute scripts vithin it.
It users vant to create their ovn scripts, they can place the script in a $HOME/bin
directory, but they have to create the $HOME/bin directory tirst.1his directory does not
exist unless a user creates it. It you look at the PATH listing in ligure 3-3, you notice
that each ot these directoriesusrlocalbin and hometoddmbin ($HOME/bin,
are listed vith the displaying ot the shell variable, $PATH.
0ARNING AOU1 7HLL &UIL1IN 'OMMANDS
A builtin connand is a command that is part ot the shell program, hence the term
builtin.1hese commands are actually compiled into the shell, thereby making the
shell an executable command containing other commands. You cannot modity or
delete builtin commands, and in tact, they are not available in any system directory.
1he only vay you can tind out more about these commands is to reter to man on
bash. 1able 3-2 shovs the common builtin commands. You have seen some ot these
commands in Chapters 1 and 2. You need to understand these commands because
they are used at the command line and in shell scripts.
90 Chapter 3 Shell asIcs
LearnIng about Shell uIltIn Commands 91
uIltIn Command DescrIptIon xample(s)
. filename Reads and execuLes commands rom . script1
speciied ilename in Lhe currenL shell
environmenL
cd Chanes Lhe currenL direcLory cd /
(See ChapLer 2 or addiLional coverae)
declare or typeset Declares a variable; Lhe -r opLion declare var2
makes Lhe variable read-only declare ~rReadOnlyvar2
echo Displays ouLpuL on Lhe screen echo$ yecho "Hello"
exec Causes a command Lo replace Lhe exec ls
currenL shell; no new process is creaLed
exit Causes Lhe shell Lo exiL wiLh a sLaLus exit 1
export LxporLs Lhe variable Lo a spawned shell; export x="Howdy!"
Lhis allows a parenL shell Lo seL a
variable LhaL can be used by a child shell
history Displays hisLory o commands history
previously enLered
kill Sends a sinal Lo a PlD. l you run kill 1409
kill ~l, you can see all Lhe kill sinals.
You use Lhis opLion Lo kill or sLop
backround processes or daemons.
let LvaluaLes an ariLhmeLic expression let x=5
local CreaLes a local variable local x=5
logout LxiLs a loin shell logout
pwd Displays currenL workin direcLory pwd
(See ChapLer 2 or addiLional coverae)
read Reads characLers rom Lhe keyboard readx
readonly Reads characLers rom Lhe keyboard; readonly y
once a variable is declared readonly,
iL cannoL be chaned
return Causes a uncLion Lo exiL wiLh a cerLain return 1
value; a reLurn value o 1 indicaLes
ailure and a reLurn value o 0 indicaLes
success
set SeLs and displays shell variables. set ~xv
1able 3-2 Some common shell builLin commands
3
0ARNING AOU1 7HLL +RAMMAR
Shell grannar is detined as the rules that must be tolloved tor proper operation
ot the shell. Basically, tor the shell to tunction correctly, a specitic set ot syntax rules
must be maintained just like in any spoken language. 1here are several tundamental
building blocks in shell grammar. You need to understand these building blocks to
best comprehend hov the shell interprets the commands given to it. A thorough
understanding can help you vhen you encounter shell errors. 1he building blocks ot
shell grammar are as tollovs
Blank
Word
Name
Metacharacter
Control operator
Peserved vord
A blank is detined as a space or a tab and is used to separate items in the shell. A vord
is detined as a sequence ot characters that is considered a single unit by the shell. A vord
is also commonly knovn as a token. A nane is a vord that consists only ot letters,
numbers and the underscore. A netacharacter is a character that is used tor a specitic
purpose by the shell, each purpose is unique to the character. A metacharacter is used
to separate vords. lor example, you have seen the greater-than symbol, >, used as a
metacharacter to redirect the output ot a command.1able 3-3 contains the metacharac-
ters used by the shell.
uIltIn Command DescrIptIon xample(s)
shift ShiLs posiLional parameLers shift 1
test LvaluaLes expressions. 1his works Lhe test ~d fileA.txt
same as Lhe expression
command. Also, you can use Lhe
expression command in place
o Lhe test command.
trap CaLches a sinal senL Lo Lhe shell; XVET8VETTIHWMKREP
displays Lhe messae "1rapped sinal 3"
when sinal 3 is senL Lo Lhe shell
1able 3-2 Some common shell builLin commands (conLinued)
92 Chapter 3 Shell asIcs
LearnIng about Shell Grammar 93
Iet`s look at an example to help you understand hov shell grammar vorks. In the tol-
loving statement, echo "This is the production file">production.txt,
the command echo is a vord.1he space immediately tolloving this command is a blank
that is used to separate this vord trom the next. 1he next vord is literally
"This is the production file". Next, the redirection operator, >, appears and
is a metacharacter. Although most ot the time you surround the redirection operator
vith a space, it is not mandatory because a metacharacter separates vords. 1he redirec-
tion operator separates the text being echoed and the tilename vhich is a name.
A control operator is a token that pertorms a specitic control tunction. It modities
hov the shell processes commands. 1able 3-4 contains the control operator symbols.
In the next example, each command is executed trom lett to right in sequence
echo "howdy" , who , pwd , date
Symbol(s) Name functIon
]] 1wo pipe symbols Causes one command Lo execuLe dependin
upon Lhe ailure o anoLher
&& 1wo ampersand symbols Causes one command Lo execuLe dependin
upon Lhe successul compleLion o anoLher
& Sinle ampersand Allows you Lo run a job in Lhe backround
, Semicolon Allows you Lo run commands in a sequence
{| LeL and rihL parenLheses Allows you Lo run a command in a subshell
] Pipe symbol Allows you Lo pass command ouLpuL Lo anoLher
command
1able 3-4 Shell conLrol operaLors
Metacharacter Symbol(s) Metacharacter Name Purpose
] 1he pipe symbol Allows you Lo pass command ouLpuL Lo
anoLher command
& Ampersand Allows you Lo run a job in Lhe backround
, Semicolon Allows you Lo sequence commands on
Lhe command line
{| LeL and rihL Allows you Lo run a command in a
parenLheses subshell
< Less-Lhan symbol Allows you Lo redirecL inpuL
> GreaLer-Lhan symbol Allows you Lo redirecL ouLpuL and creaLe
a new ile
Space Spacebar Allows you Lo separaLe words
1able 3-3 Shell meLacharacLer symbols
3
It you enter the commands in sequence vithout the semicolon, you vould receive an
error. Next you vill pertorm an exercise to help you understand the importance ot shell
operators.
1o use a shell control operator:
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Pun the tolloving commands, and then record the output.
ls , pwd , who , date , cal 12 2005
3. Pun the tolloving commands, and then record the output.
ls pwd who date cal 12 2005
4. Pun the tolloving commands, and then record the output.
{ls, pwd, who, date, cal 12 2005,}
3. Pun the tolloving commands, and then record the output.
pwd && date
6. Pun the tolloving commands, and then record the output.
date & who
7. 1o exit the 1erminal emulation program, type exit, and then press Lnter.
8. Iog out.
A reserved vord is detined as a vord that has special meaning to the shell. Such vords
cannot be used tor any other purpose unless it is in quotes or not the tirst vord in a
command. Peserved vords have specitic syntax that must be tolloved, each is ditterent.
lor example, the if, then, else, and fi statements are reserved to test conditions in
a decision and you could not use them to accomplish something else. As another exam-
ple, the while, do, and done statements are reserved tor processing loops.You vill learn
the purpose ot most ot the remaining reserved vords as you vork your vay through the
remaining chapters.
9NDRS1ANDING 'OMMAND 8YPS
Nov, that you have learned about the building blocks ot shell grammar, you need to
understand the major components, specitically, command types. Having a solid vorking
knovledge ot command types gives you the ability to properly structure commands in
your shell scripts.1he major components ot shell grammar are listed in descending order
ot complexity ot the command type.
Compound commands
Iists
94 Chapter 3 Shell asIcs
UnderstandIng Command 1ypes 95
Pipelines
Simple commands
1hink ot the command types as being structured in a pyramid in terms ot complexity,
vith simple commands at the bottom and compound commands at the top ot the pyra-
mid. Peter to ligure 3-4 tor the pyramid viev ot the command types.
SImple Commands
A sinple connand is a set ot vords separated by blanks. It is also the most basic type
ot operation you can do vithin the shell. A shell control operator terminates a simple
command. A simple command takes the general torm
command ~ot1ons arguments
As you already knov, the command is the name ot the command, the hyphen (~, signi-
ties that one or more options are to tollov. An ot1on adds extra teatures or charac-
teristics to the command. An argument is usually one or more tilenames that the
command is going to use.
A synonym or arumenL is parameLer.
Not all commands have options, nor do they all take tilenames as arguments. Because each
command has its ovn purpose and particular syntax, you should reter to the man pages tor
a given command to see specitic intormation about the command`s syntax.
Belov are a tev examples ot simple commands.You have been executing simple com-
mands since Chapter 1, so these types ot commands should be tamiliar to you.
8MT
lncreasin
command
complexiLy
LisLs
Pipelines
Simple command
Compound
commands
fIgure 3-4 Command Lypes pyramid
3
ls ~l /etc
touch filel.txt
pwd
echo "Hi"
cd /usr/sbin
clear
Lach command returns an exit status to the shell once the command completes. An exit
status ot zero indicates that the command succeeded. A nonzero exit status indicates that
the command tailed.1he concept ot an exit status vill become important in later chapters
vhen you vant to test vhether or not a command completed successtully or not.
PIpelInes
1he next level up in the command-type pyramid is the pipeline command. A pipeline
is a sequence ot simple commands separated by the pipe symbol character (],.
AlLhouh Lhe pipe symbol (]) prinLs as a solid verLical bar, iL is shown as a
broken verLical bar on mosL keyboards. You will usually ind iL above LnLer on
Lhe same key as Lhe backslash. 1he Lerm pipe and pipeline are synonymous.
1he pipeline allovs data to be passed betveen processes. A pipeline takes the tolloving
general torm
command1 ] command2 ] command2 .
1his is vhere command1, command2, and command2 are Iinux commands separated by
the pipe (], symbol.1he presence ot the three dots implies you can add several pipelines.
Belov are examples ot commands using the pipe symbol
ls ] more
ls ] sort
who ] sort ] more
history ] sort ] more
1o understand the pipeline process you need to realize that the output ot the command
on the lett side ot the pipe symbol is used as input tor the command on the right side
ot the pipe symbol. 1he command on the right modities the output in some vay prior
to displaying the output on the screen. lor example, the command ls ] more directs
the output ot the ls command as input to the more command. 1he more command
then displays one page at a time on the screen. By combining these tvo commands
together, the ls ] more pipeline causes a directory listing to be displayed one page at
a time. It you entered just ls, and the output vas more than a page, the output vould
scroll ott the screen and you vould be unable to see the portion that scrolled. Here is
another example ls ] sort ] more. 1his pipeline sorts a directory listing betore
displaying it one page at a time.
8MT
96 Chapter 3 Shell asIcs
UnderstandIng Command 1ypes 97
A ood analoy or pipelines is a waLer-ilLerin sysLem. Some people have
ilLers beneaLh Lheir kiLchen sinks Lo puriy drinkin waLer. WaLer, represenL-
in daLa, lows rom Lhe ouLside pipes as inpuL Lo Lhe ilLerin sysLem, repre-
senLin a command. 1he physical pipe represenLs Lhe Linux pipeline. 1he ilLer
puriies Lhe waLer, or in Lhe case o a pipeline, modiies iLs inpuL. 1he ouLpuL
o Lhe ilLer is inpuL inLo your lass-Lhe ouLpuL you see on your screen.
Next you vill pertorm an exercise to help you better understand the use ot the
pipe symbol.
1o use the pipe synbol:
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. 1ype ls [ more, and then press Lnter. 1he listing is displayed on the
screen. Depending upon the number ot tiles and directories to list, the listing
may appear one page at a time.
3. 1ype cat .bash_history [ more, and then press Lnter. 1he tile
.bash_history appears on the screen one page at a time.
4. 1ype who [ sort [ more, and then press Lnter. 1he output ot the who
command is sorted and displayed on the screen. Depending upon the number
ot users logged in, the output may appear one page at a time.
3. 1o exit the 1erminal emulation program, type exit, and then press Lnter.
6. Iog out.
LIst
Lp one level trom a pipeline is a list. A list is a sequence ot one pipeline or multiple
pipelines vhich are separated by one ot these operators ,, &, &&, or ]]. A list is terminated
by either a ,, &, or a nevline character. Lach ot these operators vill be discussed next.
1he , Operator
Iike pipelines, commands separated by a senicolon (,, are executed sequentially by
the shell. Lse ot the , operator takes the tolloving general torm on the command line
command1, command2
1his is vhere command1 and command2 are Iinux commands, executed in sequence, sep-
arated by the semicolon symbol.Atter the tirst command completes its execution, the shell
executes the next command in sequence. Lnlike pipes vhere the commands execute as
parts ot one process, each command separated by the semicolon is a separate process, and
is given its ovn PID. Iet`s look at an example ot a list using the , operator.1he command
list ls , pwd executes the ls command tirst. When it completes, the shell executes the
pwd command.1he subsequent command executes vhether or not the previous command
executed successtully.
8MT
3
1he & Operator
It a command is tolloved by the & operator, it is executed in the background in a
subshell. A subshell is a shell that is spavned, or generated, trom the current shell. A
background process is a process that can neither read trom nor vrite to the termi-
nal. Because ot this, the shell does not vait tor the background process to complete
betore returning the prompt.1he shell normally executes a command as a foreground
processprocess that can read trom or be vritten to the terminal. 1he shell must
vait tor a toreground process to complete betore returning the prompt.
Normally, it a command executes in the toreground, you can stop it by pressing CtrlC.
Hovever, you cannot stop a background process by pressing CtrlC. Instead, you need
to issue the kill command to stop a background process. Lse ot the & operator takes
the tolloving general torm on the command line
commandl & command2
1his is vhere command1 and command2 are Iinux commands, executed concurrently
and separated by the ampersand symbol. command1 is executed in a subshell at the same
time that command2 is executed in the current shell. Lsing the & symbol allovs both
commands to be executed at the same time. Note command2 is optional. It you leave it
ott, then the shell simply executes command1 in the background as in command1 &.
Here is an example using the & operator. In the command list ls & pwd, the ls com-
mand executes in the background, vhile the pwd command executes in the toreground.
Because they are not executed sequentially, the ls command may actually complete
atter the pwd, even though it is listed tirst. In this list command example, the command
completion sequence vould be determined by the number ot directories and tiles in
the current directory.
1he && Operator
1he && operator causes the shell to execute a command only it the immediately
preceding command completes successtully (exit status ot zero,.1his is ditterent trom
the & operator. With the && operator, the commands are executed sequentially in the
same shellnot concurrently in a subshell. Lse ot the && operator takes the tollov-
ing general torm on the command line
command1 && command2
1his is vhere command1 and command2 are Iinux commands separated by tvo
ampersand symbols. 1he command specitied as command2 only executes it command1
executes successtully (vith an exit status ot zero,.
WiLh Lhe & operaLor, even i Lhe irsL one ails, Lhe second command execuLes.
WiLh Lhe && operaLor, i Lhe irsL command ails, Lhe second command will
RIZIV execuLe. 8MT
98 Chapter 3 Shell asIcs
UnderstandIng Command 1ypes 99
lor example, in the list rm filel.txt && pwd, the rm filel.txt command executes
tirst. It it completes successtully, the pwd executes atter it. It rm filel.txt tails (exit sta-
tus is nonzero,, because the tile to be removed does not exist, the pwd never executes.
Iet`s look at another example. In the list lsxxx && pwd, the pwd command never exe-
cutes because the lsxxx command does not exist and returns a nonzero exit status.
1he [[ Operator
1he [[ operator causes the shell to execute a secondary command in the event that
the tirst command tails. Lse ot the ]] operator takes the tolloving general torm on the
command line
command1 ]] command2
1his is vhere command1 and command2 are Iinux commands separated by tvo pipe sym-
bols. Lven though the ]] operator uses tvo pipe symbols, its use here is unrelated to the
tunctionality ot a single pipe symbol in pipelines. 1he command specitied as command2
only executes it command1 executes unsuccesstully (vith an exit status not equal to zero,.
lor example, in the list rm filel.txt ]] pwd, it the rm filel.txt command tails
to execute successtully (nonzero exit status,, the second command, pwd, executes. It the
tirst command in the list, rm filel.txt ]] pwd, completes successtully, the pwd
command never executes. In the tolloving list, lsxxx ]] pwd, the lsxxx command
does not exist and returns a nonzero exit status tor being unsuccesstul, so the pwd com-
mand executes.
CombInIng Commands and Operators
1he shell allovs you to combine operators on the command line.When using the &&
and ]] operators, the commands in the list are executed sequentially. In a list that
includes both the && and ]] operators, equal precedence exists betveen the tvo
operators. 1he operator that appears tirst, trom lett to the right, is executed tirst. In
a list that only includes both the , and & operators, equal precedence exists betveen
these tvo as vell. 1he operator appearing tirst, in lett to right order, is executed tirst.
Hovever, in a list that includes all tour operators, the && and ]] operators are eval-
uated betore the , and & operators.
Iet`s combine a tev ot these operators to see hov they vork together. In the list example,
date, pwd && who ] more, there are tvo simple commands, date and pwd, separated
by the control operator, ,. 1hen the && operator is used vith the who ] more pipeline.
1his list executes the who ] more pipeline only it the preceding commands, date, pwd
complete successtully. 1hus, the date command runs tirst. 1hen, the pwd command exe-
cutes. Next, the shell must determine it the preceding command tailed. It so, it stops and
processes no other statements. It the commands have succeeded, then the who ] more
command executes. Peter to the tirst command list in ligure 3-3.You can see that both
commands on the lett and right side ot the && operator executed.
3
In the preceding example, all commands should execute. Hovever, in the command,
date, pwdx && who ] more vhere pwdx is misspelled, only the date command exe-
cutes. 1he pwdx tails because it is invalid. Because the sequence ot commands on the lett
side ot the && operator tailed, the pipeline on the right side does not execute.
Consider this list example, date, pwd ]] who ] more vhich uses the ]] operator.
Here the who ] more pipeline only executes it the preceding commands, date, pwd,
do not complete successtully. ligure 3-3 shovs a sample screen shot ot this list.
Compound Commands
At the top ot the command-type pyramid, is the compound command, thus, it is the
most povertul ot the command types. Conpound connands allov you to pertorm
calculations, assign variables, pertorm decision tests, and create loops. A compound com-
mand can include any ot the previous command types plus the tolloving types
Group commands
Lxpressions
Decision constructs
Iooping constructs
Group commands and expressions vill be discussed here. Decision and looping con-
structs vill be discussed in Chapters 6 and 7, respectively.
fIgure 3-5 OuLpuL o Lwo lisL commands
ln Lhe irsL command,
date and pwd are
execuLed, Lhen Lhe who
is piped Lo more
ln Lhe second command,
date and pwd are
execuLed. However, Lhe
who ] more command
is noL execuLed because
Lhe irsL commands
date,pwd execuLe
successully
100 Chapter 3 Shell asIcs
UnderstandIng Command 1ypes 101
Group Commands
A group connand is a list ot commands either executing in a subshell or the current
shell. A group command is made up ot one ot the tolloving tormats
{list|
{ list, }
1he {list} Group Command
With a {list| group command, the list ot commands is executed in a subshell. Because
the commands in the list are executed in a subshell, any variables assigned vithin the list
do not remain intact once the list completes. Iet`s look at an example. In ligure 3-6,
the variable assignment y=5 sets y to the value ot 3. Next the echo $y command dis-
plays the contents ot the variable y, vhich is 3. In the next statement, vhich is a list
group command, {y=50|, y is set to the value ot 30 in a subshell. Hovever, the result
ot the last echo $y command shovs that y is still set to 3. 1his is because the com-
mands in the {list| group command are executed in a shell spavned trom the cur-
rent shell. 1he current shell is not attected by commands executed in the shell spavned
trom it.You vould use this group command vhen you vanted a variable to remain unat-
tected by a command in the current shell.
fIgure 3-6 Use o Lhe {list| roup command
LxecuLed in Lhe
currenL shell
LxecuLed in a spawned
shell; Lhereore "y"
doesn'L chane
3
A variable is assined by inpuLLin a name, Lhe equal sin, and Lhen Lhe value.
For example, y=5 assins Lhe value 5 Lo Lhe variable "y." You musL precede
a variable name wiLh a dollar sin in order Lo use Lhe conLenLs. For example,
in Lhe command echo$y Lhe dollar sin immediaLely prior Lo Lhe variable
name, "y," is required. l you leL o Lhe dollar sin, as in, echoy, Lhe shell
would liLerally display Lhe leLLer "y."
You could also use the {list| group command structure it you vanted to execute
multiple commands in the background. Lsing the & operator causes a command to be
executed in the background as in who &. Hovever, you can only place one command
betore the & operator. With the group command, you can execute multiple commands
in the background. lor example, the group command {pwd, who, ls| & causes each
command vithin the parentheses to be executed collectively in the background. 1hey
vill take only one PID.
When a subshell is spawned, iL Lakes on a unique PlD. lLs PPlD is Lhe PlD o
Lhe parenL shell LhaL spawned iL.
1he { list, } Group Command
With a {list, } group command, the list ot commands is executed in the current
shell.1he list must be terminated vith a semicolon , or nevline. Because the commands
in the list are executed in the same shell, any variables assigned vithin the list remain
once the list completes.
1his type ot group command is usetul vhen you vant to apply other operators to the
commands in the list as a vhole. lor example, it you execute the who and ls ~l com-
mands, their output may scroll ott the screen. You could use the pipe operator and the
more command to scroll the output one screentul at a time.You could enter the com-
mands as a group command, { who, ls ~l,} ] more. 1hen, the collective output
ot the commands betveen the { } symbols vould be piped to the more command.
ligure 3-7 shovs a screenshot ot the previous group command. Notice that the
collective output is piped to the more command.
Iet`s look at another example dealing vith variables. In ligure 3-8, the variable
assignment y=5 sets y to the value ot 3. Next the echo $y command displays the
contents ot the variable y, vhich is 3. In the next statement, { y=50, }, y is set
to the value ot 30 in the current shell. 1he result ot the last echo $y command
shovs that y nov possesses the nev value30. Again, this is because the commands
in the list execute in the current shell.
8MT
8MT
102 Chapter 3 Shell asIcs
UnderstandIng Command 1ypes 103
It you look again at ligure 3-6 and compare it vith ligure 3-8, you see that in the
{y=5| group command, the value ot y does not change because the statement is exe-
cuted in a subshell and does not attect the current value ot y. In ligure 3-8, the
{ y=50, } group command does change it because it is pertormed in the same shell.
fIgure 3-8 1he use o Lhe {list,} roup command
LxecuLed in Lhe
currenL shell
LxecuLed in Lhe same
shell as y=5, so "y"
chanes Lo 50
fIgure 3-7 Use o Lhe {list,l,} command roupin several commands
3
xpressIons
An epression is used vhen you vant to assign a value to a variable, pertorm an arith-
metic calculation using variables, or test tor values meeting certain conditions. An
expression is made up ot one ot these tormats
{{expression||
expression
1he {{expression}} command
You use the {{expression|| compound command to evaluate an arithmetic opera-
tion. 1he expression generally takes one ot the tolloving torms
{{var1ao1e~name = va1ue1 oerator va1ue2||
{{va1ue1 oerator va1ue2||
1his is vhere va1ue1 and va1ue2 are variable assignments or integers. 1he term
oerator represents an arithmetic operation that is pertormed on the values. A partial list
ot operators is shovn in 1able 3-3.1he tirst statement ot the expression is used tor variable
assignment, as in {{y=5 + 6||. Note that var1ao1e~name is a variable assigned by you.
Operator Name xample
:EVMEFPIREQI 1he incremenL operaLion {{t=x++||
:EVMEFPIREQI 1he decremenL operaLion {{t=x~~||
** LxponenLiaLion {{x=2**3||
* NulLiply {{x=4*5||
/ Division {{x=10/2||
+ AddiLion {{x=10+2||
~ SubLracLion {{x=10~2||
% Remainder {{r=100%4||
== Lqual Lo {{$x==2||
!= NoL equal Lo {{$x!=2||
>= GreaLer Lhan or equal Lo {{$x>=$y||
<= Less Lhan or equal Lo {{$t<=10|)
> GreaLer Lhan {{$x>5||
< Less Lhan {{$t<$x||
&& AND operaLion {{$y==5&&$t==5||
]] OR operaLion {{$y==$r]]$t==5||
1able 3-5 Various operaLors used wiLh Lhe {{expression|| compound command
104 Chapter 3 Shell asIcs
UnderstandIng Command 1ypes 105
You can use let"expression" insLead o {{expression|| or
ariLhmeLic operaLions. 1he "expression" in Lhe let"expression"
sLaLemenL uses Lhe same synLax as {{expression||. For example,
{{y=500||isequivalenttolet"y=500".
Next you vill become tamiliar vith the syntax ot expressions because you vill use
expressions in tuture chapters.
1o understand epressions:
1. Iog in to the Iinux operating system as a user, and then open a 1erminal
emulation vindov.
2. 1o multiply tvo numbers, type {{x=5 * 6}}, and then press Lnter. 1he
variable x nov contains the number 30. Hovever, nothing is displayed yet.
3. 1o add a variable and a number, type {{y=$x+4}}, and then press Lnter. 1he
variable y nov contains the number 34. Again, nothing is displayed yet.
4. 1o display the contents ot the tvo variables, type echo $x $y, and then press
Lnter. 1he numbers 30 and 34 are displayed on your screen.
3. 1o exit the 1erminal emulation program, type exit, and then press Lnter.
6. Iog out.
1he Increment and Decrement Operators
Nov, look at the increment and decrement operators listed in 1able 3-3. 1hese are
extremely usetul operators because they allov you to add one to a value or subtract one
trom a value etticiently in a script.1vo addition symbols, + +, are used as the increment
operator.1vo subtraction symbols, ~ ~, are used as the decrement operator. Iet`s say you
vanted to increment the value ot a variable named valuel, by 1, you could use the
increment operator as tollovs
{{valuel++||
1he incremenL operaLor can be used in a scripL as a counLer when
you wanL Lo counL iLems you have processed. OLher ways Lo
incremenL a value are: {{value1=value1+1||, let"value1++", or
let"value1=value1+1"
8MT
8MT
3
ligure 3-9 illustrates the use ot the increment operator to increment a value. In the tig-
ure, value1 is set to 100 and then incremented using the valuel++ statement. Notice
the echo statements result in 100 betore and 101 atter the value is incremented.
Nov, suppose you vanted to decrement the value ot the variable named valuel by 1.
You could use the decrement operator as tollovs
{{valuel~~||
ligure 3-10 illustrates the use ot the decrement operator to decrement a value.You can
see the variable vith a value ot 100 is displayed betore it is decremented and then the
value changes to 99 atter the variable contents are decremented.
1he xponentIatIon, MultIplIcatIon, DIvIsIon, AddItIon, SubtractIon, and
RemaInder Operators You are probably tamiliar vith the mathematical concepts ot
exponentiation, multiplication, division, addition, and subtraction. 1he idea ot placing
the remainder into a variable may be nev to you, it vill be covered at the end ot this
section. lirst, look at hov these operators are set up in examples so you can understand
hov to implement them in shell scripts. 1hese operators are important because they
allov the shell to pertorm calculations and can be used in scripts.
fIgure 3-9 Usin Lhe incremenL operaLor Lo incremenL a value
106 Chapter 3 Shell asIcs
UnderstandIng Command 1ypes 107
lirst consider exponentiationraising a number to a pover. 1o do this, you use tvo
asterisks, **. Iook at an example
{{x = 4||
{{y = 2**x||
In this example, the variable x is set to 4. In the expression, {{y=2**x||, the vari-
able y is equal to 2 raised to the pover ot x vhich is 4. 1hus, the ansver is y
equals 16.
Here are some multiplication, division, addition, subtraction, and remainder examples to
consider. ligure 3-11 shovs the results ot these expressions.
{{x = 4||
{{y = 2||
{{m=x*y||
{{d=x/y||
{{a=x+y||
{{s=x~y||
{{r= x%y||
fIgure 3-10 Usin Lhe decremenL operaLor Lo decremenL a value
3
When usin Lhe % operaLor, Lhe variable Lo Lhe leL o Lhe % operaLor is divided
by Lhe variable Lo Lhe rihL o Lhe % operaLor. 1hen, Lhe remainder o Lhis
division is placed inLo Lhe variable name. So, in {{x=10%2||, "x" equals
zero, and in {{x=11%2||, "x" has a remainder value o 1.
Arithmetic expressions tollov precedence. 1he order ot vhat takes precedence is listed
in 1able 3-6. Operators listed vithin the same cell ot the table have equal precedence,
so it tvo operators vith equal precedence are given in an expression, they are evaluated
trom lett to right. lor example, the increment and decrement operators have equal
precedence and are evaluated betore anything else.
You can alter the order by placing parentheses around lover-precedence operations so that
they are evaluated betore higher ones. It you have multiple parentheses, the operations
vithin the innermost parentheses are pertormed tirst. lor example, in the statement
Operators
:EVMEFPIREQI++, :EVMEFPIREQI
**,*,/,%
+,~
<=,>=,<,>
==,!=
&&
ll
1able 3-6 Precedence o ariLhmeLic operaLions lisLed in descendin order
8MT
fIgure 3-11 1he resulLs o various ariLhmeLic expressions
108 Chapter 3 Shell asIcs
Chapter Summary 109
{{y=5+3*2||, the multiplication operation is evaluated tirst. So, the number 3 is multi-
plied by the number 2, resulting in 6. 1hen, the number 3 is added to the number 6, and
y is set to 11. Hovever, it you placed parentheses around the addition operation, as in
{{y={5+3|*2||, it vould evaluate tirst. So, 3 is added to 3 resulting in 8.1hen, the num-
ber 8 is multiplied by the number 2, and y is set to 16.
Next you vill complete an exercise to help you understand the use ot parentheses in
expressions.
1o understand the use of parentheses in epressions:
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. 1ype {{x=100-3**2}}, and then press Lnter to change the value ot x by
tirst raising 3 to the pover ot 2 and then subtracting the result trom 100.
3. 1ype {{y={100-3}**2}}, and then press Lnter to change the value ot y
by tirst subtracting 3 trom 100 and then raising that result to the pover ot 2.
4. 1ype echo $x $y, and then press Lnter. 1he numbers 91 and 9409, are dis-
played on the screen respectively.
3. 1o exit the 1erminal emulation program, type exit, and then press Lnter.
6. Iog out.
Lxpressions operaLe only on inLeers. Division by zero resulLs in an error.
1he || expressIon ]] command You can use the expression command, or
the test command, to test attributes ot a tile or directory, pertorm character string com-
parisons, and pertorm numeric comparisons.A string is a set ot one or more alphanumeric
characterseither a number or a character.1he expression commands have sev-
eral tormats. You vould use the if command to make decisions vith the expres~
sion command.1he if command is covered in Chapter 6.
'HAP1R 7UMMARY
1he shell can be invoked by either logging in or by entering the name ot the shell at
the shell prompt.1he shell uses startup tiles to customize the user`s environment.1he
login tiles are etcprotile, -.bash_protile, and -.bashrc. 1he etcprotile script tile is
read and executed tor all users as they log in.1he root user account can only change
8MT
3
this script tile.1he other tvo, -.bash_protile and -.bashrc, located in each user`s
home directory, are executed it they exist. Lach user can change these tiles.1he
-.bash_logout is executed vhen a user logs out and can be moditied by the user.
1he shell has its ovn variables that are reserved specitically tor its use. 1hey must
be entered in uppercase. 1he PATH shell variable contains a list ot directories the
shell searches vhen attempting to locate a script or command. 1o display the con-
tents ot a shell variable, precede it vith a dollar sign, as in this example $PATH.
1he lile System Hierarchy Standard supports placing scripts used by all users in the
usrlocalbin directory and having users place their ovn scripts in -bin. 1he
-bin directory must be created betore any scripts can be placed in it.
Shell builtin commands are commands that are compiled as part ot the shell.You
can`t tind them in any directory, and you have to reter to the man pages tor the
shell instead ot tor an individual command.
It is important to understand the grammar ot the shell because the shell is a lan-
guage and a strong understanding ot the tundamentals can help you troubleshoot
problems vhen you are entering commands. 1he basic building blocks ot shell
grammar are blanks, vords, names, metacharacters, control operators, and reserved
vords. A blank is a space or tab and is used to separate items entered at the shell
prompt. A vord is a sequence ot characters the shell uses as a unit. A name is a
vord consisting only ot letters, numbers, and the underscore. A metacharacter is a
character that has a special purpose to the shell. A control operator modities hov
the shell processes commands. A reserved vord is a vord that is used by the shell
and is generally a command.
1he shell provides tor several command types. 1hese include simple commands,
pipelines, lists, and compound commands.You need to understand these ditterent
types in order to properly construct commands to accomplish a certain task vith-
out the threat ot generating an error. A simple command is a set ot vords separated
by blanks. A pipeline is used to process data betveen commands. A list is a series ot
pipelines separated by a control operator. A compound command allovs you to
assign variables, pertorm computations, and execute decisions and loop structures.
6VIW 5US1IONS
1. is the login startup tile that is read tirst.
a. etcprotile
b. -.bash_logout
c. -.bash_protile
d. -.bashrc
110 Chapter 3 Shell asIcs
RevIew QuestIons 111
2. Which term is used to detine a space or tab in shell grammar
a. metacharacter
b. vord
c. name
d. blank
3. A process alvays executes in a subshell.
a. toreground
b. background
c. simple command
d. control operator
4. 1he script tile is read and executed vhen the user terminates
his session.
a. etcprotile
b. -.bash_logout
c. -.bash_protile
d. -.bashrc
3. Which term is used to describe a character that has special meaning to the shell
a. token
b. vord
c. blank
d. metacharacter
6. A process can read data trom the terminal.
a. toreground
b. background
c. control operator
d. token
7. Which is the name ot the symbol that allovs the output ot one command to be
tiltered as input to another
a. greater-than
b. pipe
c. double greater-than
d. less-than
3
8. is the symbol used tor executing a job in the background ot
the shell.
a. &
b. <
c. ,
d. ?
9. is the symbol used to separate commands in a list, vhich are
executed sequentially.
a. ,
b. <
c. >>
d. ?
10. is the operator that is used vhen you vant one command to
execute only it another command executes successtully.
a. *
b. ]]
c. &&
d. <
11. Which group command executes commands in a subshell
a. {{n++||
b. {{expression||
c. { list },
d. {list|
12. You use the group command to execute commands in the
current shell.
a. {{n++||
b. {{expression||
c. { list },
d. {list|
13. Which group command is used to evaluate arithmetic operations
a. list
b. {{expression||
c. { list },
d. {list|
112 Chapter 3 Shell asIcs
RevIew QuestIons 113
14. Which ot the tolloving is an example ot the increment operator
a. {{n}}
b. ((n--,,
c. ((n,,
d. ((n,,
13. 1he remainder symbol is .
a. *
b. /
c. &
d. %
16. Which command is synonymous vith the expression command
a. pwd
b. test
c. {{expression||
d. {list}
17. Which term describes a set ot one or more alphanumeric characters
a. token
b. string
c. list
d. blank
18. A command that is part ot the shell is called a command.
a. export
b. import
c. builtin
d. inherent
19. Which command is used to send a signal to a PID
a. pwd
b. kill
c. ls
d. signal
3
20. 1he shell variable is used to locate the directory a command
is stored in.
a. $path
b. $PATH
c. etcprotile
d. $TMOUT
,ANDSON 4ROJC1S
Project 3-1
In this project, you vill change the -.bash_protile tile so you can see it execute as part
ot the login process. 1his vill help reintorce your understanding ot its role in the login
process.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1ype vi .bash_profile, and then press Lnter. 1he shell script is displayed on
the screen. Note there vill be other commands currently there.
3. Press Shift+G to move the cursor to the bottom ot the tile.
4. 1ype o to open a line ot text in vi, and then input the tolloving lines ot code to
change the -.bash_protile tile
echo "Executing the .bash_profile login file."
echo "A list of current users:"
who
echo "The current directory is:"
pwd
echo "The end of the .bash_profile login file."
3. Save the tile, and then close the editor.
6. Lxecute the script.
7. Pecord the output.
8. Delete the lines ot code in the -.bash_protile tile that you added.
9. Close your vindov, and then log out.
Project 3-2
In this project, you vill change the -.bashrc tile so you can see it execute as part ot the
login process.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1ype vi .bashrc, and then press Lnter. 1he shell script is displayed on the screen.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
114 Chapter 3 Shell asIcs
Hands-on Projects 115
3. Go to the end ot the tile and append the tolloving lines ot code
echo "Executing the .bashrc login file."
date
echo "The end of the .bashrc login file."
4. 1elnet to your system.
3. As you are logging in, notice the screen, and record vhat occurs.
6. Compare the execution ot Project 3-1 and this project. Which script executes tirst
7. Delete the lines in the -.bashrc tile that you added.
8. Save the tile, and then close the editor.
9. Close your vindov, and then log out.
Project 3-3
In this project, you vill create a shell script and change the .bash_logout tile to execute
that shell script.You vill display the user`s login name set in the etcprotile, as vell as
display the host name tolloved by the date. linally, you vill test the script. 1he goal ot
this project is to reintorce your knovledge ot the login and logout shell script tiles.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1ype vi LogOut, and then press Lnter.
3. Insert the tolloving lines to display the user`s login name, hostname, date, and
time the user logged out
echo ~n $LOGNAME "logged out" $HOSTNAME "at"
date
4. Save the tile, and then close the editor.
3. Open the .bash_logout tile, and then insert the IogOut script you just created
at the bottom ot the screen.
6. Press Shift+G to move the cursor to the bottom ot the tile.
7. 1ype o to open a line ot text in vi.
8. 1ype bash LogOut, and then press Lnter.
9. Save the tile, and then close the editor.
10. 1elnet to your system.
11. Iog out, notice the screen, and then record the results.
12. Close all vindovs.
Project 3-4
In this project, you vill reintorce your understanding ot shell variables.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
3
2. Create a shell script named Project3-4 located in a directory supported by the
lile System Hierarchy Standard.
3. You need to pertorm the steps shovn in pseudocode in the order shovn
Change to the /tmp directory
Change to your home directory
Display the previous working directory using a shell
variable
Display your home directory using a shell variable
Display your home directory using an alternate method to
using a shell variable
Display the amount of time the shell will wait for user
input before the current shell is terminated using a shell
variable
Set the previous variable to 120
Display the amount of time the shell will wait for user
input before the current shell is terminated using a
shell variable
Set the previous variable to 0
4. Save the tile, and then close the editor.
3. Lxecute the script.
6. Pecord the commands used, and then record or print your script.
7. Close your vindov, and then log out.
Project 3-5
In this project, you vill reintorce your understanding ot vhat happens to variables vhen
using group commands.You vill also see hov a tormula changes vhen parentheses are
added or removed trom an arithmetic expression.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named Project3-S located in a directory supported by the
lile System Hierarchy Standard that contains the tolloving lines ot code
a=100
b=10
y=0
echo $a $b $y
{ {{y={$a+4}*$b}}, echo $y }
echo $y
{ {{y=$a+4*$b}}, echo $y}
echo $y
{ {{y={$a+4}*$b}}, echo $y, }
echo $y
{ {{y=$a+4*$b}}, echo $y, }
echo $y
3. Print the script.
,ERHWSR
4VSNIGX
116 Chapter 3 Shell asIcs
Hands-on Projects 117
4. Save the tile, and then close the editor.
3. Lxecute the script.
6. Write dovn the output to the right ot each command that executes. Why does
the value ot y either change or remain the same atter each ot the echo $y
statements that are on a line by themselves
7. Close your vindov, and then log out.
Project 3-6
In this project, you vill use the increment operator as a counter. You vill also use the
decrement operator to reintorce your understanding ot the use ot expressions.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named Project3- located in a directory supported by the
lile System Hierarchy Standard.
3. 1he script needs to pertorm the tolloving pseudocode in the order shovn
Set a variable named "n" to 10
Display the contents of "n"
Use the correct expression to increase "n" by 1
Display the contents of "n"
Use the correct expression to decrease "n" by 1
Display the contents of "n"
Increase the variable "n" again using a different
expression
Display the contents of "n"
Decrease the variable "n" again using a different
expression
Display the contents of "n"
4. Save the tile, and then close the editor.
3. Lxecute the script, and then record the command used.
6. Pecord or print your script.
7. Close your vindov, and then log out.
Project 3-7
In this project, you use additional arithmetic operators in the {{expression|| com-
mands.1he goal ot this project is to reintorce your understanding ot arithmetic operations.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named Project3-7 located in a directory supported by the
lile System Hierarchy Standard.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
3
3. 1he script needs to pertorm the tolloving pseudocode in the order shovn
Set a variable named "x" to 10
Set a variable named "y" to 100
Display the result of dividing "y" by "x" and place the
result into variable "t"
Display the result of dividing "y" by 0
Display the result of multiplying "y" by "x" and place the
result into variable "t"
Display the result of adding "y" and "x" and place the
result into variable "t"
Display the result of subtracting "x" from "y" and place the
result into variable "t"
Display the result of raising "y" to the power of 2 and
place the result into variable "t"
Display the result of taking the remainder of "y" divided
by "x" and place the result into variable "t"
4. Save the tile, and then close the editor.
3. Lxecute the script, and then record the commands used.
6. Pecord or print your script.
7. Close your vindov, and then log out.
Project 3-8
In this project, you vill gain an understanding ot hov to use various command types at
the command line.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named Project3-8 located in a directory supported by the
lile System Hierarchy Standard.
3. 1he script needs to pertorm the tolloving pseudocode in the order shovn
Display the list of current users seguentially followed by
the current directory
Display the list of current users as a background process
Update the modification time of a file named cactus.dat
Issue the command to display a message indicating a file
named cactus.dat was removed only if the command to remove
it succeeds
Issue the command to display a message indicating a file
named cactus.dat was not removed only if the command to
remove it fails
Display a long listing of the /tmp directory one screen at
a time
4. Save the tile, and then close the editor.
3. Lxecute the script, and then record or print your script.
6. Close your vindov, and then log out.
,ERHWSR
4VSNIGX
118 Chapter 3 Shell asIcs
Case Projects 119
'AS 4ROJC1S
Case 3-1
1MI has hired your consulting tirm to assist their Iinux users.You get a call trom Marge
vho is just learning the Iinux system. She has saved up several questions and needs you
to respond to these issues
1. She needs to locate additional documentation on the cd, pwd, and the history
commands, but she is having ditticulty tinding anything.
2. She has a script that one ot the programmers vrote. It takes a long time to execute.
She vants to be able to execute it and have the prompt immediately return.
3. She vould like to add a message to all users as they log in. She vould like a dit-
terent message added tor her ovn account.
Case 3-2
1he Santiago Iav lirm has recently purchased a Iinux computer system.You interviev
the users and determine a shell script is needed to exit a user`s process vhen he or she has
not pressed a key atter 60 seconds. When each user logs in, a list should be displayed ot
current users so everyonse can see vho is logged in and presumably, vorking. Additionally,
the Santiago Iav lirm vants each user to see vhat system he or she is logged on to. Also,
the tirm vould like a calendar tor the current month to be displayed. (Hint 1his requires
moditication to the -.bash_protile tile.1he TMOUT shell variable must be set and exported
to 60 seconds., linally, the -.bash_logout tile needs to display the message Lxiting the
Santiago system vhen a user exits a 1erminal emulation vindov.
'EWI
4VSNIGX
'EWI
4VSNIGX
3
121
',%48)6

8,) 7,)00 )2:-6321)28


-RXLMWGLETXIV]SY[MPP
9RHIVWXERHVIHMVIGXMSR
9RHIVWXERHTEXXIVRQEXGLMRK
9RHIVWXERHXLIYWISJUYSXMRK
9RHIVWXERHI\TERWMSR
0IEVREHHMXMSREPGSQQERHW
-
n this chapter, you vill understand hov to redirect the tlov ot a command`s
input or output. You vill also learn hov to match specitic patterns to access
a subset ot the tiles in a given directory and hov to use quoting to protect
certain metacharacters. You vill see hov various commands and operators
expand into additional items. linally, you vill learn some additional commands
that vill help you pertorm your job better in a Iinux operating system
environment.
9NDRS1ANDING 6DIRC1ION
Redirection means to direct the tlov trom one place to another. In Iinux, you can
redirect the tlov ot input or output trom their normal detault location. Why vould you
vant to do this Pedirection gives you tlexibility in terms ot vhere your data is either
coming trom (input, or going to (output,. lor example, you might redirect output it you
vanted to save the result ot a command. Because output redirection typically results in
a tile being generated, you are able to reviev the tile that contains the output ot the
command, either presently or at a later date. Input redirection is used less otten than
output redirection. With input redirection, the detault location tor a command`s input
is changed. Hovever, most ot the commands that accept tilenames as part ot their syntax
usually don`t require the input redirection operator.
Iinux reters to standard input (stdin) as the detault location tor inputting commands.
1he detault location tor standard input is the keyboard. Iinux reters to standard output
(stdout) as the detault location tor outputting commands. Standard output detaults to the
display screen. 1he term standard error (stderr) is the detault location ot errors gener-
ated trom commands. Standard errors also detault to the display screen. Pedirection allovs
you to change the detault locations ot standard input, standard output, and standard error.
Iinux uses the term file descriptor to describe a number that reters to a tile. Lach time
a command runs, it has three tile descriptorsone tor stdin, stdout, and stderr. It uses
these to handle input and output operations as vell as error handling. 1able 4-1 shovs
the tile descriptors tor standard input, output, and error.
Linux LreaLs Lhe keyboard and Lhe display screen as iles. Linux also LreaLs
oLher hardware devices such as Lape backup devices, loppy devices, and
CD-RON devices similarly. l you execuLe Lhe ls command in Lhe /dev
direcLory, you will see Lhe device iles.
8MT
fIle fIle DescrIptor LocatIon
SLandard inpuL 0 /dev/sLdin
SLandard ouLpuL 1 /dev/sLdouL
SLandard error 2 /dev/sLderr
1able 4-1 File descripLors or sLandard inpuL, ouLpuL, and error
122 Chapter 4 1he Shell nvIronment
UnderstandIng RedIrectIon 123
RedIrectIng Standard Input
Pedirecting input causes a program to read trom a tile instead ot the keyboard. 1he sym-
bol to redirect input is the less-than symbol (<,. 1he arrov points tovard the command
tor redirecting input. 1he general torm is
command < f11ename
1his is vhere command is a command, and f11ename is a Iinux tile. lor example, the
sort command typed in vithout any options sorts the data trom standard input, or the
keyboard. Hovever, you can sort a tile it you use a redirection symbol, tor example,
sort < personnel.txt. 1his command takes the input tor the sort command
directly trom the personnel.txt tile instead ot the keyboard. 1he original tile remains
intact and the output is sent to standard output, or the screen.
Next you vill learn hov to redirect input. In this exercise, you vill enter employee
names in a payroll tile. You vill use the sort command to sort the payroll tile, vhich
vill be redirected as input to it.
1o redirect input:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a tile named pay.dat in your $HOME/bin directory that includes the
tolloving records
Smith, Jay
Patel, Arnie
Trang, Vingh
Adams, Claude
DeRue, Jacgues
3. Save the tile, and then close the editor.
4. 1o redirect input, type sort < pay.dat, and then press Lnter. See ligure 4-1.
1he data is sorted on the screen. 1he original pay.dat tile is intact.
3. 1o verity the original tile has not changed, type cat pay.dat. See ligure 4-1.
Notice the order ot employee names is the same as you originally input it in
Step 2.
6. Close the vindov, and then log out.
4
RedIrectIng Standard Output
Pedirecting output causes the command to redirect its output trom the display screen
to a tile. Pedirecting output is usetul vhen you vant to keep the output ot a command
tor later reviev. 1here are tvo torms ot redirecting standard output. 1hey are redirecting
output to create a nev tile and redirecting output to append to an existing tile.
RedIrectIng Output to Create a New fIle
Lsing the single greater-than (>, symbol to redirect output allovs you to send the output
ot a command to a tile. It the tile exists, its current contents are overvritten. It the tile
does not exist, it is created. Notice that the arrov points avay trom the command tor
redirecting output. You might redirect output to a nev tile it you vanted to keep the
listing ot a command tor later reviev. 1he general torm is
command > f11ename
lor example, the ls command displays a directory listing to standard output, or the
display screen. You can redirect standard output to a tile named lslist.txt by typing
ls > lslist.txt. 1his results in standard output being redirected to the specitied
tile. When you use a single greater-than symbol, it causes a nev tile to be created as long
as a tile by that name doesn`t already exist. It the tile exists, then that tile is overvritten.
fIgure 4-1 lnpuL redirecLion
SLep 3
SLep 4: same employee
order as oriinally inpuL
124 Chapter 4 1he Shell nvIronment
UnderstandIng RedIrectIon 125
Iet`s look at an example.
ls > file2.txt
cat file2.txt
who > file2.txt
cat file2.txt
1he ls > file2.txt command causes the output ot the ls command to be redirected
to a tile named tile2.txt. 1he output is placed at the beginning ot the tile. It tile2.txt
already exists, any previous data in that tile is lost. 1he second command, cat
file2.txt, proves the output has been redirected. 1he third command, who >
file2.txt, causes the output ot the who > file2.txt command to be redirected
to the same tile, overvriting any previous data. Again, the output is placed at the beginning
ot the tile. Lltimately, you only end up vith the output trom the who > file2.txt
command as is proven by the last command, cat file2.txt. ligure 4-2 shovs the
results ot the previous commands.
You can redirecL inpuL and ouLpuL in a sinle command. For example, Lhe com-
mand sort~r<input.txt>output.txt sorLs Lhe ile inpuL.LxL in
reverse sorL order, and Lhen redirecLs LhaL ouLpuL Lo a ile named ouLpuL.LxL. 8MT
fIgure 4-2 OuLpuL redirecLion Lo creaLe a new ile
4
RedIrectIng Output to Append to a fIle
You use tvo greater than symbols to append output to a tile. It the tile exists, the output
ot the command adds its output just belov the last line ot the existing tile. It the tile
does not exist, it is created. You pertorm the redirect append (>>, operation it you vant
to preserve the current contents ot a tile. You pertorm the redirect create (>, operation
it you vant to remove the previous contents ot the output tile. 1he general torm is
command > f11ename
Consider vhat happens it you issue the tolloving sequence ot commands
ls > file2.txt
cat file2.txt
who >> file2.txt
cat file2.txt
1he tirst command`s output is redirected to the tile, the second command`s output is
placed atter the tirst. In this case, you vould have the output ot both commands in one
tile. ligure 4-3 shovs a screenshot ot these commands.
fIgure 4-3 RedirecLin ouLpuL and appendin iL Lo a ile
126 Chapter 4 1he Shell nvIronment
UnderstandIng RedIrectIon 127
Compare ligures 4-2 and 4-3 and notice hov they ditter. In ligure 4-2, tile2.txt contains
just the output ot the very last command. In ligure 4-3, tile2.txt contains the output ot
both commands.
Next you vill redirect output.
1o redirect output:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1o redirect output and create a nev tile, type ls -l > file3.txt, and
then press Lnter. 1he output ot the ls ~l command does not appear on the
screen because it vas sent to the tile named tile3.txt.
3. 1o redirect output and append to a tile, type pwd >> file3.txt, and then
press Lnter. 1he output ot the pwd command does not appear on the screen
because it vas sent to the tile named tile3.txt.
4. 1o redirect output and append to a tile, type date >> file3.txt, and
then press Lnter. 1he output ot the date command does not appear on the
screen because it vas sent to the tile named tile3.txt.
3. 1o redirect output and append to a tile, type echo "The End" >>
file3.txt, and then press Lnter. Again, the output ot the echo command
does not appear on the screen.
6. 1o display the contents ot the tile, type cat file3.txt, and then press
Lnter. See ligure 4-4, notice that the output that vas redirected in Steps 2
through 3 nov appears on the screen.
7. 1o exit the 1erminal emulation program, type exit, and then press Lnter.
8. Iog out.
fIgure 4-4 RedirecLin ouLpuL Lo boLh creaLe and append Lo a ile
SLep 6: ouLpuL rom
SLeps 2-5 is redirecLed
Lo screen
4
RedIrectIng Standard rror
Most commands also send their error messages to the screen. It you vant to capture that
output to a tile tor later reviev, you can redirect standard error. Iet`s say you are vorking
on the Iinux help desk tor a company, and a customer calls saying she is getting an error
message. One solution is to have the customer redirect standard error to a tile, and then
send the tile to you tor inspection. Pedirecting standard error is similar to redirecting
standard output except you must reter to the tile descriptor, 2, tor standard error to redirect
it. 1he general torm is
2>f11ename
lor example, it you vant an error message trom the rm command to be redirected, you
enter rm 2>rmlist.err. 1hen, you can issue the cat rmlist.err command to
display the contents ot the rmlist.err tile.
1ypically, standard error is combined vith standard output. Hovever, to redirect standard
output and standard error to ditterent tiles, you enter rm >rmlist.txt 2>rmlist.err.
You implement this torm ot redirection it you vant to send standard output and standard
error to ditterent tiles.
You typically redirect both standard output and standard error it a command runs auto-
matically, tor example, at night vhen you are not there to see the output on the screen.
In this case, you vould vant to have the output sent to a tile tor reviev the next day.
SeLLin up scripLs Lo run auLomaLically will be discussed in ChapLer 12.
It you vant standard output and standard error to go to the same tile, the general torm is
&>f11ename
1he use ot the ampersand (&, tells the shell to redirect standard error and standard out-
put to a tile other than the detault, you use the ampersand method vith the redirection
symbol. It you vant to redirect both standard output and standard error in one tile, you
also use the method using the ampersand. lor example, the tolloving command tells the
shell to redirect both standard output and standard error to the same tilename.
rm &>rmlisting.txt
Next you vill learn hov to redirect standard output and standard error.
8MT
128 Chapter 4 1he Shell nvIronment
UnderstandIng RedIrectIon 129
1o redirect standard output and standard error:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1o redirect standard output and standard error to ditterent tiles, type { ls -l,
who, rm t5} >listing.txt 2> errlisting.txt, and then press Lnter.
1here is no output displayed to the screen. (^ote1he tile t3, it it exists, should be
removed prior to pertorming this step so an error vill be generated.,
3. 1o display the contents ot the listing.txt tile, type cat listing.txt, and
then press Lnter. See ligure 4-3. 1he output is displayed on the screen.
4. 1o display the contents ot the errlisting.txt tile, type cat errlisting.txt,
and then press Lnter. See ligure 4-3. 1he output is displayed on the screen.
3. 1o combine standard output and error to a single tile, type { ls -l,
who, rm t5} &>combolist.txt, and then press Lnter.
6. 1o display the contents ot the combolist.txt tile, type cat combolist.txt,
and then press Lnter. See ligure 4-6. 1he output is displayed on the screen.
7. Close the vindov, and then log out.
fIgure 4-5 RedirecLin sLandard ouLpuL and sLandard error Lo separaLe iles
SLep 3: displays conLenLs
o ile
SLep 4: displays conLenLs
o ile
4
9NDRS1ANDING 4A11RN 1A1CHING
Pattern natching is a technique that uses metacharacters to match characters based
upon a certain pattern. lor example, you use pattern-matching techniques to list all tiles
that started vith a j. Or, it you vant to match all characters vith a .dat extension, you
can use pattern-matching techniques. Pattern matching usually results in a subset ot the
total number ot items available. lor example, it you vant to display all tiles beginning vith
a j, then this vould most likely be a subset ot the total number ot tiles in the given
directory.
You can Lhink o paLLern maLchin as "searchin" or speciic iles or direcLories
in a iven direcLory.
1here are several methods tor matching various patterns ot characters. 1he pattern-
matching techniques are as tollovs
1o match any character use the (*, symbol
1o match a single character use the (?, symbol
1o match any one ot several characters use the (..., symbol
8MT
fIgure 4-6 RedirecLin sLandard ouLpuL and sLandard error Lo Lhe same ile
SLep 6: displays Lhe
conLenLs o Lhe ile
130 Chapter 4 1he Shell nvIronment
UnderstandIng Pattern MatchIng 131
MatchIng Any Character
You use the asterisk symbol to match any character.1his type ot pattern matching usually
concludes in the largest number ot results returned because it matches any character.You
use this pattern-matching technique it you vant to match patterns that match a lot ot
characters.1he asterisk symbol matches any character position. lor example, the command
cp *.dat /dirA tells the shell to copy all tiles vith a dat extension in the tilename
to the directory named dirA. 1he command ls ~l t* tells the shell to list all ot the
tiles that begin vith a lovercase t.1he command rm G*.txt tells the shell to remove
all tiles that begin vith an uppercase G and that have a txt extension.
Next you vill learn hov to match any character.
1o natch any character:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a directory named PatternMatch1 in the $HOME directory.
3. Change directory locations to PatternMatch1.
4. Lse the touch command to create these tiles in the PatternMatch1 directory
file1.dat, GreatBig.tt, file2.dat, file3.dat, fileS.tt, and file.tt, and then
list all the tiles vith the ls command.
3. 1o list all tiles that begin vith the letter t, type ls f*, and then press
Lnter. See ligure 4-7. Only tiles beginning vith an t are displayed.
6. 1o list all tiles that begin vith the letter G, type ls G*, and then press
Lnter. See ligure 4-7. Only tiles beginning vith a G are displayed.
7. 1o list all tiles vith an extension ot txt, type ls *.txt, and then press
Lnter. See ligure 4-7. Only tiles vith an extension ot txt are displayed.
8. 1o list all tiles that begin vith the letter t and have an extension ot txt,
type ls f*.txt, and then press Lnter. See ligure 4-7. Only tiles beginning
vith an t ano having an extension ot txt are displayed.
9. Close your vindov, and then log out.
4
AnoLher Lerm LhaL is used Lo describe Lhe concepL o maLchin any characLer
is "wildcard." SomeLimes an asLerisk is called Lhe wildcard symbol. 1he Lerm
comes rom playin wiLh a deck o cards where a card can be any card Lhe
player chooses. 1hus, paLLern maLchin is synonymous wiLh wildcardin.
Match a SIngle Character
1o match a single character position, you use the question mark symbol. 1his type ot
pattern matching is usually more restrictive than matching any character because you can
actually control vhich character position to match. lor example, it you vanted to display
only tiles that had a 2 in their tourth character position regardless ot vhat tollovs the
tourth character position, you vould enter ls ???2*. It you had entered ls *2*, the
result vould be any tile vith a 2 anyvhere in the tilename, so the use ot ? is required
to establish proper placement ot the character tor vhich you are searching.
Next you vill pertorm a search to match a single character.
1o natch a single character:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a directory named PatternMatch2 in the $HOME directory.
3. Change directory locations to PatternMatch2.
4. Lse the touch command to create these tiles in the PatternMatch2 directory
filenonkey.tt, filesilly.dat, file123.dat, t1.dat, t2.dat, t3.dat, tell.dat,
teleconnute.dat, and tv.tt.
8MT
fIgure 4-7 PaLLern maLchin o any characLer
SLep 5: lisLs all iles
beinnin wiLh ""
SLep 6: lisLs all iles
beinnin wiLh "G"
SLep 7: lisLs all iles wiLh a
.LxL exLension
SLep 8: lisLs all iles
beinnin wiLh "" and
havin a .LxL exLension
132 Chapter 4 1he Shell nvIronment
UnderstandIng Pattern MatchIng 133
3. Iist all the tiles vith the ls command.
6. 1o list all tiles that begin vith a t, are tolloved by a single character, and have
a dat extension, type ls t?.dat, and then press Lnter. See ligure 4-8.
Notice that only the matching tiles are listed.
7. 1o list all tiles that begin vith a t, tolloved by a single character and have
three characters in the extension, type ls t?.???, and then press Lnter.
See ligure 4-8. Notice that only matching tiles are listed.
8. 1o match tiles containing tour characters vith a three-character extension,
type ls ????.???, and then press Lnter. See ligure 4-8, notice that only
the matching tile is listed.
9. 1o remove all tiles that begin vith a t, have only one remaining character
in the second character position, and have a three-character extension, type
rm t?.???, and then press Lnter. See ligure 4-8, notice that only the
matching tiles, in this case, t1.dat, t2.dat, t3.dat, and tv.txt are removed.
ln some versions o Linux you may receive an inLeracLive prompL rom Lhe rm
command askin i you wanL Lo deleLe each ile. 1o remove Lhe iles in ques-
Lion, you musL answer in Lhe airmaLive.
10. Iist all the tiles using the ls command.
11. 1o list the tiles previously removed, type ls t?.???, and then press Lnter.
See ligure 4-8. A message appears indicating there are no such tiles.
12. Close your vindov, and then log out.
fIgure 4-8 PaLLern maLchin a sinle characLer
SLep 6: lisLs all iles LhaL
maLch Lhe paLLern
SLep 7: lisLs all iles LhaL
maLch Lhe paLLern
SLep 8: only one ile
maLches Lhe paLLern
SLep 9: only iles maLchin
Lhe paLLern are removed
SLep 11: a no iles exisL;
messae is displayed
8MT
4
Match Any One of Several Characters
1he use ot square brackets allovs you to match any one ot the characters contained
vithin the square brackets. You use this type ot pattern matching tor matching tiles con-
taining uppercase and lovercase tilenames. Iinux tilenames are case sensitive, meaning
that the tolloving tiles are considered ditterent lLN.DA1, lun.Dat, tun.dat, luN.Da1
and tuN.dAt. Consequently, it you vant to match any tiles beginning vith either an
uppercase 1 or a lovercase t, you vould enter ls Tt*. Iike the question mark
symbol, use ot square brackets is positional.
1his pattern-matching technique also allovs you to match a range ot characters. lor
example, it you vant to list all tiles that begin vith any ot the uppercase letters I
through P, you enter ls L~P*.1o match these same lovercase characters, you enter
ls l~p*.
Next you vill use pattern matching to match one ot several characters.
1o natch one of several characters:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Change to the PatternMatch2 directory.
3. Lse the touch command to create these additional tiles in the PatternMatch2
directory zorro.tt, pecan.dat, apples.dat, vater.dat, and bread.tt.
4. Iist all the tiles.
3. 1o list all tiles beginning vith either an t or t, type ls ft]*, and then
press Lnter. See ligure 4-9. Only matching tiles are listed.
6. 1o list all tiles beginning vith tel and having either an l or an e in the
tourth character position, type ls telle]*, and then press Lnter. See
ligure 4-9, notice that only the telecommute.dat and tell.dat tiles are displayed.
7. 1o list all tiles that begin vith a letter in the range ot t through z, type
ls f-z]*, and then press Lnter. See ligure 4-9. Notice that only matching
tiles beginning vith any letter starting vith t through the letter z are listed.
8. 1o list all tiles that begin vith tile vith the letters m through s as the
titth character position, type ls filem-s]*, and then press Lnter. See
ligure 4-9. Only matching tiles are displayed.
9. Close your vindov, and then log out.
134 Chapter 4 1he Shell nvIronment
UnderstandIng the Use of QuotIng 135
9NDRS1ANDING 1H 9S Of 5UO1ING
It you have to use one ot the metacharacters discussed in Chapter 3, or one ot the pattern-
matching characters, you need a vay to distinguish betveen the literal symbol and the
symbol`s use as a metacharacter or pattern-matching character.1his is called quoting and
it allovs you to distinguish betveen the literal value ot the symbol and the symbols used
as code. 1o do this, you must use one ot these three symbols
Backslash (\,
Single quote (',
Double quote (",
A ackslash (@)
A backslash is also called the escape character. When you use the backslash symbol
vhen you are quoting, it allovs you to preserve only the character immediately tollov-
ing it, vith the exception ot a nevline character. lor example, consider the greater-than
symbol. You knov that the greater-than symbol is a shell metacharacter that redirects
output to create a nev tile. 1o stop the shell trom interpreting the greater-than symbol
as the redirection symbol, you need to protect it. It you vant to create a tile named
tools~, you do so by entering the tolloving command touch tools\>. In this
example, it is the backslash symbol that preserves the literal meaning ot the greater-than
symbol. It you enter touch tools>, the shell generates an error because the shell uses
fIgure 4-9 NaLchin more Lhan one characLer
SLep 5: lisLs all iles
beinnin wiLh "" or "L"
SLep 6: only Lwo iles
are maLched
SLep 7: only iles LhaL
bein wiLh a leLLer in Lhe
rane o "" Lhrouh "z"
are maLched
SLep 8: lisLs all iles
beinnin wiLh "ile" and
havin a leLLer in Lhe rane
o "m" Lhrouh "s" in Lhe
ourLh posiLion
4
the greater-than symbol as a redirection operator, and it is expecting a tilename to tollov
this operator.
ln eneral, iL is noL advisable Lo use meLacharacLers as symbols when namin
a ile.
Next you vill use the backslash symbol to preserve the meaning ot a metacharacter.
1o use the backslash to preserve the literal neaning of a netacharacter:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1ype touch TimeKeeper>, and then press Lnter. An error message is displayed
on the screen. 1his is because the backslash vas not included in the tilename,
so the shell tried to interpret the greater-than symbol as a redirection operator
and tailed because a tilename vas not tolloving the greater-than symbol.
3. 1o create a tile vith the greater-than metacharacter in the tilename, type
touch TimeKeeper\>, and then press Lnter. 1he prompt returns.
4. 1ype ls TimeKeeper>, and then press Lnter. Again, you receive an error
because the ls command could not handle the greater-than metacharacter
correctly.
3. 1o list the tile vith the greater-than metacharacter in the tilename, type
ls TimeKeeper\>, and then press Lnter. Notice that this time, the tile is
displayed.
6. 1o exit the 1erminal emulation program, type exit, and then press Lnter.
7. Iog out.
A SIngle Quote ()
Iike the backslash, a single quote is used to protect the literal meaning ot metacharac-
ters. Hovever, it ditters trom the backslash in that it can protect all characters vithin the
single quotes. 1he only character it cannot protect is itselt. Lsually, you use single
quotes it you vant to display a quote trom someone. lor example, the command
echo 'Joe said "Have fun!"' results in the shell placing double quotes around
the text Have tun'.
A single quote cannot occur vith other single quotes even it preceded by a backslash. lor
example, the command echo 'Joe said 'Have fun'' vould not result in the shell
placing single quotes around the text Have tun`. Instead, the shell simply displays Joe
said Have fun. 1o display the quotes, you enter echo 'Joe said "Have fun" '.
Next you vill protect text and metacharacters using single quotes.
8MT
136 Chapter 4 1he Shell nvIronment
UnderstandIng the Use of QuotIng 137
1o use the single quotes to preserve the literal neaning of characters vithin
the quotes:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1ype touch ' "Hello", said Tonya', and then press Lnter to create a
tile vith this unusual name.
3. Iist this tile vith the ls ' "Hello", said Tonya' command. 1he tile is
listed on the screen.
4. Insert the tolloving lines ot code to create and display the tile
touch ''Hello', said Tonya'
ls ''Hello', said Tonya'
1he text Hello does not have quotes around it vhen the tilename is displayed.
Pemember, you cannot embed single quotes vithin single quotes.
3. Close your vindov, and then log out.
A Double Quote ()
You use double quotes to protect all symbols and characters vithin the double quotes.
Hovever, double quotes vill not protect these literal symbols $, ', and \, even though
they are metacharacters. Pecall that single quotes vill protect these symbols. It you vant
to display these characters or have them as part ot a tilename, you need to use single
quotes. lor example, the command echo '$5.00' displays the text s3.00 correctly.
It you vant to display a single quote, as an apostrophe, then you need to use double
quotes. lor example, to display the text, Poss` larms, Inc., you use double quotes because
single quotes cannot contain single quotes. 1o create a tile named Micki`s tile, you
enter touch "Micki's file".
Next you vill preserve the literal meaning ot a metacharacter using double quotes.
1o use double quotes:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1o correctly display the text Ive gone fishin, enter echo "I've gone
fishin'", and then press Lnter. Notice that the text is correctly displayed
on the screen.
3. 1o correctly display the text )ake von 8S00.00, enter echo 'Jake won
$500.00', and then press Lnter. Again, the text is correctly displayed on the
screen. You could have entered it this vay too echo Jake won '$'500.00
because you only need to protect the dollar sign.
4. 1o correctly display the text Youve earned 8S.00, enter echo "You've"
earned '$5.00', and then press Lnter. You are required to torm the state-
ment this vay because the apostrophe (a single quote, in the contraction
4
must be protected vith double quotes. 1he dollar sign must be protected vith
the single quotes.
3. Close your vindov, and then log out.
9NDRS1ANDING )XPANSION
Lpansion is the process ot changing metacharacters and special symbols into something
else. 1he shell uses special symbols to expand or substitute vords that are entered on the
command line.You have already seen expansion as it applies to the shell variables in previous
chapters. lor example, $HOME expands, or turns, into your home directory. 1he $PATH
variable expands into the list ot directories the shell uses to search tor locating commands.
Lxpansion occurs vhen you use these variables. 1here are several types ot expansion but
only a tev vill be discussed in this chapter. 1hey are listed belov
1ilde
Parameter and variable
Command substitution
1Ilde xpansIon
A tilde-prefi is the part ot a command that begins vith the tilde symbol (-, and is
tolloved by additional characters. 1he tilde (-, expands to the user`s login name home
directory. lor example, it you execute the cd - command, your current directory
changes to your home directory. It you enter the command cp -victory.dat tmp, the
tile named victory.dat trom your home directory vould be copied to the tmp directory.
It the tilde-pretix is part ot the -+ command, then the value ot the shell variable PWD is
substituted tor the tilde-pretix. lor example, it you enter the command echo -+, your
current vorking directory is displayed. In this case, the tilde-pretix vith the plus sign
achieve the same results as the pwd command.
It the tilde-pretix is part ot the -~ command, then the value ot the shell variable OLDPWD
is substituted tor the tilde-pretix and hyphen. It you enter the command echo -~, your
previous vorking directory is displayed.
Parameter (or VarIable) xpansIon
Paraneter epansion, in general, substitutes values tor parameter or variable names.
Parameters and variables are discussed turther in Chapter 3. lor nov, think ot them as
names that can contain values. 1he dollar sign ($, is used tor parameter expansion. lor
example, you can set the variable 1ext1 to be Please enter menu selection vith the
command Textl="Please enter menu selection: ". Hovever, in order to
access the contents, you must precede the variable vith the dollar sign. So,
echo $Textl displays the contents ot 1ext1 on the screen. In this example, the vari-
able $Textl is substituted vith its contents, Please enter menu selection.1here are a
138 Chapter 4 1he Shell nvIronment
UnderstandIng xpansIon 139
variety ot vays you can achieve parameter substitution depending upon the expansion
command you choose to use.
Use of the _REQIa method
1he use ot braces is designed to allov you to mix variables and numbers in the shell.
lor the most part their use is not needed, but there are some circumstances vhere braces
are required. 1his type ot expansion takes the tolloving general torm
${name}
lor example, suppose you vork tor an international bank and you vant to display a cur-
rency value symbol that you have stored in a variable named currency. You also vant to
display a credit transaction by a customer to shov Credit s300.00.1o do so, you enter
the tolloving statements
currency='$'
echo "Credit" ${currency}500.00
1hese commands display vhat you intended on the screen-Credit s300. It you don`t
include the braces around the variable, you get unexpected results. Here the variable
currency is equal to the number 300. ligure 4-10 demonstrates this use ot braces tor
parameter substitution trom the previous example. Notice the second example in
ligure 4-10 does not contain braces. Without them, the dollar sign and the number are
not displayed.
fIgure 4-10 Use o braces in parameLer subsLiLuLion
4
SpecIfyIng Part of a Value UsIng ${REQISJJWIXPIRKXL}
You can use parameter expansion to specity a portion ot a parameter`s value by using
the tolloving torm
${name:offset:1ength}
1he name value is the name ot the variable. 1he offset position is the beginning posi-
tion vithin the value you vant, and the length number is the number ot positions ot
the value you vant. 1he offset position begins at zero. 1he use ot braces is required.
It you leave them ott, you get unexpected results. Consider an example vhere you have
a parameter named p that contained the value abcde. Ietter a is in position, or ott-
set, zero, letter b is in position, or ottset, one, and so on. It you vant to specity the
third and tourth character positions tor c and d, then you use the statement
echo ${p:2:2}.1he tirst 2 is the ottset and the second 2 is the length. It you vant
to display the tirst tour positions, you use the statement echo ${p:0:4}. A practical
use ot this type ot parameter expansion might be using a portion ot your Social Security
Number (SSN, as a passvord. Many systems set your initial passvord to the last tour dig-
its ot your SSN. So, the statement, password=${SSN:5:4} initially sets the passvord
to the last tour digits ot your SSN.
SpecIfyIng a VarIable's Length
1here may be times vhen you vant to determine the length ot a variable. lor instance,
it you vant to determine it a user has entered the appropriate number ot characters in
a tield on the screen. 1o determine the length ot a variable you use the tolloving gen-
eral torm
${#var1ao1e}
1o display the length tor a variable named 1, you type echo ${#T}.
Next you vill complete an exercise to increase your understanding ot parameter expansion.
1o understand paraneter epansion:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1o set a variable tor use, type p="56789", and then press Lnter.
3. 1o display the tirst tvo character positions ot p, type echo ${p:0:2}, and
then press Lnter. See ligure 4-11. 1he characters, 3 and 6, are displayed.
4. 1o display tvo character positions ot p starting vith the third position, type
echo ${p:2:2}, and then press Lnter. See ligure 4-11. 1he characters, 7
and 8 are displayed.
3. 1o display the last character position ot p, type echo ${p:4:1}, and then
press Lnter. See ligure 4-11. 1he last character is displayed.
140 Chapter 4 1he Shell nvIronment
UnderstandIng xpansIon 141
6. 1o verity the need tor braces, type echo $p:4:1, and then press Lnter. See
ligure 4-11. Notice that the text 3678941 is displayed, vhich is not vhat
you intended.
7. 1o display the length ot p, type echo ${#p}, and then press Lnter. See
ligure 4-11. 1he numeral tive is displayed indicating that the length ot the
variable is tive positions.
8. Close your vindov, and then log out.
Command SubstItutIon
Connand substitution allovs you to substitute the output ot a command in place ot
the command itselt. 1his is typically used in combination vith parameter or variable
substitution. lor example, you knov that the pwd command displays your current vork-
ing directory. What it you vant to keep this intormation You can use command substi-
tution to set a variable to equal the output ot the pwd command. 1hen, you can display
the contents ot the variable using parameter substitution. 1here are tvo torms ot com-
mand substitution. 1hey are
${command|
`command`
In both cases, command is a Iinux command.1he ${command| is the never ot the tvo
torms ot command substitution and treats everything vithin the parentheses as part ot
the command.
fIgure 4-11 Use o parameLer expansion
SLep 3: displays irsL Lwo
characLer posiLions o "p"
SLep 4: displays Lwo
characLer posiLions o
"p" sLarLin wiLh Lhe
Lhird posiLion
SLep 5: displays Lhe lasL
characLer posiLion o "p"
SLep 6: incorrecL LexL is
displayed
SLep 7: indicaLes lenLh o
Lhe variable
4
1he sinle back quoLe (`) is used in `GSQQERHD. lL is on Lhe same key as Lhe
Lilde symbol.
Iet`s look at an example. It you enter the t=`ls` command, tolloved by the echo $t
command, the contents ot the variable named t are the output ot the ls command.
It you choose to use the other syntax, you enter t=${ls|.
You can also nest command substitutions. Nesting means placing a command substitu-
tion vith another command substitution. 1he innermost nested command executes tirst.
lor example, in the t=${ls ${pwd|| command, the content ot the variable t tirst
contains a listing ot the current vorking directory, vhich is the output ot the ${pwd|
command that is substituted tirst. Next, the output ot the ls command is substituted.
Lltimately, the contents ot t are the directory listing ot the current directory in this
example.
You cannoL use Lhe sinle back quoLes when nesLin. You will eL unexpecLed
resulLs.
Next you vill complete an exercise to help you understand command substitution.
1o understand connand substitution:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1ype echo "User" ${whoami} "is on system" ${hostname}, and
then press Lnter. 1he text Lser username is on system sstemname is dis-
played on the screen. See ligure 4-12. Note that toddm is the username
shovn and the system name is s1.Your username and sstemname vill be
ditterent.
3. 1ype echo "Your current directory is: " ${pwd}, and then press
Lnter. 1he text Your current directory is oire.torname is displayed on the
screen. In ligure 4-12 the current directory shovn is hometoddmCh4.
Your oire.torname vill be ditterent.
4. 1o implement an alternate torm ot command substitution, type
echo "Your current directory is: " `pwd`, and then press Lnter.
See ligure 4-12. Notice that the results are the same tor this step and the
previous one.
3. 1o display the date, type echo "Today is" `date`, and then press Lnter.
1he text 1oday is .urrentoate is displayed on the screen. Your .urrentoate
vill be ditterent than vhat is shovn in ligure 4-12.
8MT
8MT
142 Chapter 4 1he Shell nvIronment
LearnIng AddItIonal Commands 143
6. 1o display the current year, type echo "The year is" `date +%Y`, and
then press Lnter. 1he text 1he year is .urrentear is displayed on the
screen. Your .urrentear vill be ditterent than vhat is shovn in ligure 4-12.
7. Close your vindov, and then log out.
0ARNING %DDI1IONAL 'OMMANDS
In this section, you vill learn several additional Iinux commands.1hese commands vill
help enhance your Iinux skills, they are highly usetul commands vhen implemented in
shell scripts. 1he tolloving is a list ot additional commands
find
tr
tee
mail
1he JMRH Command
1he find command allovs you to search tor tiles in the directory tree. You use this
command vhen you do not knov vhere a tile is located. 1his command locates the
directory the tile is in. You can also use this command vith options to tind tiles that are
a certain size, ovned by a specitic user, or older than a specitied number ot days. 1he
find command locates the tiles in the directory tree based upon the criteria specitied
fIgure 4-12 Use o command subsLiLuLion
SLep 3: your direcLory will
be dierenL
SLep 2: user name and
sysLem name display
4
in the options. While the find command has numerous options, only a tev vill be cov-
ered in this section. It you vant to tind out about additional options, reter to the man
pages tor the find command. 1he find command takes this general torm
find ath exress1on
1his is vhere ath is either a tull or partial path. Note that only the current directory
is searched it you do not specity a path. An exress1on can be comprised ot options,
tests, and actions. Only tests vill be discussed in this section. 1here are several available
actions, but the detault action is to display text to the screen. 1able 4-2 shovs a list ot
some ot the more important f1nd tests.
Consider the example shovn in the table used tor tinding a specitic tile named ltm1,
find ~name ltml.1he output returned tor this example is the tull path to the tile in
the tree. You don`t have to be in the directory the tile is located in to use the find com-
mand.1he find command looks in all directories starting in the current directory.1his
is a particularly usetul command vhen you don`t knov vhere a tile is located.
You can use pattern matching techniques vith the find command, too. lor example,
to tind all tiles vith a tirst character in the range ot a-c, you enter find a~c*.
It you vant to locate all tiles that have not been moditied in the last seven days, you
enter find ~mtime 7. A list ot tiles not moditied in the last seven days appears. 1he
find command searches all subdirectories. Lse ot the moditication option is very help-
tul vhen you vant to clean up your system by deleting older tiles.
Another application ot the find command is listing all tiles as opposed to directories.
1o do so you enter find ~type f, and a listing ot all tiles along vith their tull paths
1est DescrIptIon xample
~mtime Finds iles modiied a speciied find ~mtime 5
RYQFIVSJHE]W RYQFIVSJHE]W ao
~name TEXXIVR Searches or a direcLory based upon find ~name ltm1
a speciied TEXXIVR
~size RYQFIV Finds iles LhaL are a minimum size. find ~size 1k
1he RYQFIV speciies Lhe size used Lo
compare. ALer Lhe number, you can
use a Lerm. Some valid Lerms are:
"k" or kilobyLes
"c" or byLes
~type Finds iles o a cerLain Lype. Some find ~type d
valid Lypes:
"d"=direcLory
""= ile
~user YWIVREQI Find iles owned by YWIVREQI find ~user toddm
1able 4-2 A ew find LesLs
144 Chapter 4 1he Shell nvIronment
LearnIng AddItIonal Commands 145
is displayed. 1o locate only directories, you enter find ~type d, and a listing ot all
directories is displayed. 1he find command is also usetul tor tinding tiles created by a
particular user. 1o display all tiles ovned by a user named Sally, you enter
find ~user Sally, and all ot her tiles are displayed.
You can even locate tiles that are a specitic size. 1o tind all tiles that are at least 10 kilo-
bytes (10,000 characters,, you enter find ~size l0k. 1his application is usetul tor
locating large tiles in the directory tree that might be occupying a lot ot disk space.
Next you vill complete an exercise to help you understand the find command.
1o understand the find connand:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1o locate all tiles and directories in the current directory, type find, and
then press Lnter. All tiles and directories appear on the screen.
3. 1o locate directories, type find -type d, and then press Lnter. 1his time,
only directories appear on the screen.
4. 1o locate tiles, type find -type f, and then press Lnter. Nov, only tiles
appear on the screen.
3. 1o tind tiles over 1 kilobyte, type find -size 1k, and then press Lnter.
Only tiles at least 1 kilobyte in size appear.
6. 1o tind tiles ovned by a user, type find -user username. Peplace
username vith your ovn name. All tiles that you ovn are displayed.
7. Close your vindov, and then log out.
1he XV Command
1he tr command translates or deletes characters. It is very usetul tor translating lover-
case characters to uppercase vhen testing tor user input in a shell script. It takes the tol-
loving general torm
tr ot1on set1 set2
1his is vhere set1 are either characters or classes ot characters that are to be translated
into characters or classes ot characters specitied in set2.1he original characters in set1
are translated into the characters in set2. It you vanted to translate all lovercase letters to
uppercase using a class ot characters, you enter tr :lower: :upper:. Or, you could
reverse the tvo and convert uppercase to lovercase as in tr :upper: :lower:.
lrom a programming standpoint, translating characters gives you greater control over the
characters because tever possible variations exist. As a shell programmer, there may be
times vhen you request a user to input data at a prompt. You can use the tr command
to translate all the characters to uppercase, and continue your script based on uppercase
input data. lor example, suppose you vrote a shell script that checked vhether a user
4
entered a Y, tor Yes, in order to pertorm a certain task. What it the user entered a
lovercase y Pemember that uppercase and lovercase letters are ditterent. One option
is to vrite a script that accounts tor all the possibilities, or you could just translate the
lovercase y to an uppercase Y, and then check tor this.
You can use Lhe "-d" opLion Lo deleLe characLers.
Next you vill use the tr command to translate uppercase and lovercase letters.
1o understand the tr connand:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1o translate lovercase characters to uppercase, type tr :lower:]
:upper:], and then press Lnter. 1he cursor moves to the beginning ot the
next line. 1he tr command is avaiting your input.
3. At the beginning ot the next line, type linux is fun!, and then press
Lnter. See ligure 4-13. 1he characters are translated to uppercase.
4. Press Ctrl+D to terminate the command.
3. 1o translate uppercase characters to lovercase, type tr :upper:]
:lower:], and then press Lnter. 1he cursor moves to the beginning ot the
next line. 1he tr command is avaiting your input.
6. At the beginning ot the next line, type THIS is cool., and then press
Lnter. See ligure 4-13. 1he uppercase characters are translated to lovercase.
1he already existing lovercase characters do not change.
7. Press Ctrl+D to terminate the command.
8. 1o translate just one character, type tr y Y, and then press Lnter.
9. At the beginning ot the next line, type The answer is "y"., and then
press Lnter. See ligure 4-13. 1he only character translated is y. It is trans-
lated trom lovercase to uppercase.
10. Press Ctrl+D to terminate the command.
11. Close your vindov, and then log out.
8MT
146 Chapter 4 1he Shell nvIronment
LearnIng AddItIonal Commands 147
1he XII Command
1he tee command is a usetul command because it reads trom standard input and vrites
both to standard output and to tiles. You use this command it you vant to see the out-
put ot a command as vell as keep the output ot the command in a tile tor later reviev.
1he tolloving is the general torm
tee ot1on f11e
1he tee command only has a tev options, the most important one is the ~a option used
tor appending. Consider a possible use tor this command. One example might be dis-
playing the output ot the who command on the screen and then capturing that same out-
put to a tile tor later reviev. You can use the tee command to accomplish this. Suppose
you enter the who ] tee wholist.txt command. Pecall that the vertical bar is the
pipe symbol discussed in Chapter 2. 1he output goes to the screen, and then the tee
command sends the output to the vholist.txt tile. 1his ditters trom redirection because
vith the tee command you get output in tvo placesthe screen and a tile. With (or
vithout, redirection, you only get output in one placeeither the screen or a tile.
Next you vill use the tee command to send output to tvo places.
fIgure 4-13 Use o Lhe tr command
SLep 3: characLers are
LranslaLed Lo uppercase
SLep 6: already exisLin
lowercase characLers do
noL chane
SLep 9: "y" is LranslaLed
Lo uppercase
4
1o understand the tee connand:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1o display the list ot current users and send the output to a tile named
output.txt, type who [ tee output.txt, and then press Lnter.
ligure 4-14 shovs possible results ot this command.Your results vill ditter.
3. Display the content ot the output tile.
4. 1o display the list ot current users and append the output to the output.txt
tile, type who [ tee -a output.txt, and then press Lnter. 1he listing ot
users should be similar to vhat vas displayed in Step 2.
3. Display the contents ot the output tile. See ligure 4-14. Notice that the cat
command is used to display the output.txt tile. 1he original output that vas
sent to this tile in Step 2 as vell as the output appended in Step 4 is shovn.
Your results vill ditter.
6. 1o display the current directory, and then append the output to the
output.txt tile, type pwd [ tee -a output.txt, and then press Lnter.
Your present vorking directory is displayed.
7. Display the contents ot the output.txt tile. See ligure 4-14. Notice that the
intormation trom Steps 2 and 4 is included as vell as the result ot the pwd
command trom Step 6. Your results vill ditter.
8. Close the vindov, and then log out.
fIgure 4-14 Use o Lhe tee command
SLep 2: your ouLpuL
will dier
SLep 7: displays ouLpuL or
SLeps 2, 4, and 6
SLep 5: displays ouLpuL or
SLeps 2 and 4
148 Chapter 4 1he Shell nvIronment
LearnIng AddItIonal Commands 149
1he QEMP Command
1he mail command is used to send and receive electronic messages. 1o run the mail
command, simply type mail at the command prompt. Because most people are already
tamiliar vith the concepts ot sending and receiving e-mail, you vill next pertorm an
exercise to shov you hov it vorks on the Iinux operating system.
1o use the mail connand:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1o send an e-mail to a user, type mail username, and then press Lnter. Be
sure to replace username vith your ovn username. 1he mail command
displays a Subject line.
3. On the Subject line, type Price Quote, and then press Lnter. 1he cursor
moves to the beginning ot the next line. 1his is one ot the message lines
vhere you vill enter the text you vant to send.
4. On the tirst message line, type The price guote for customer 1001A
for Purchase Order 1122-EG is $199.99., and then press Lnter.
On the next message line, type Thanks,, and then press Lnter. 1he cursor
moves to the beginning ot the next message line. See ligure 4-13.
3. Press Ctrl+D. 1he Cc line appears. 1his is tor Courtesy copy in case you
vant to send this message to another user.
6. Press Lnter. 1he Iinux prompt returns.
7. Wait a tev minutes tor the mail daemon to send the message. 1o receive your
mail, type mail, and then press Lnter. An ampersand appears. 1his is the
mail prompt. See ligure 4-13. One or more lines are displayed indicating
you have a message. You should see the letter N tor Nev message and a
number to the right ot the N.1his is the message number used tor reter-
encing the message.
8. 1ype in the message number ot your nev message, and then press Lnter. 1he
message appears. In ligure 4-13, the message number is 1.
9. Peviev the message, press g, and then press Lnter to quit mail.
10. Close your vindov, and then log out.
4
'HAP1R 7UMMARY
Pedirection changes the detault locations ot standard input, standard output, and
standard error. 1he symbol tor redirecting standard input is the less-than symbol
(<,. 1he symbol tor redirecting standard output and creating a nev tile is the single
greater-than symbol (>,. 1he symbol tor redirecting standard output and appending
it to a tile is made up ot tvo greater-than symbols (>,.
Pattern matching can be used to tind characters. 1he symbol to match zero or more
characters is the asterisk (*,. 1he symbol to match a single character position is the
question mark (?,. 1o match several characters, you enclose a list or range ot char-
acters to be matched vithin brackets, (...,.
1he use ot quotes preserves the literal meaning ot metacharacters. 1he backslash, \,
preserves the meaning ot the character immediately tolloving it. Lsing tvo single
quotes, '...', protects characters vithin the quotes. Single quotes preserve the
meaning ot all characters vithin them vith the exception ot another single quote.
1he use ot tvo double quotes, "...", preserves the meaning ot all characters
vithin double quotes vith the exception ot $, ', and \.
Lxpansion is the process ot changing the metacharacters into something else. 1he
shell uses special symbols knovn as metacharacters to expand vords or substitute
values. 1he types ot expansion discussed in this chapter include tilde, parameter, or
variable, and command. 1ilde expansion converts the metacharacter - into your
home directory. Parameter, or variable, expansion allovs you to use metacharacters
fIgure 4-15 Use o Lhe mail command
SLep 7: "N" indicaLes
new messae
SLep 4: messae line
150 Chapter 4 1he Shell nvIronment
RevIew QuestIons 151
to combine numbers and characters. 1o vork vith portions ot a parameter, you use
the (${name:offset:1ength}, torm. 1o determine the length ot a parameter,
you use the (${#name}, torm.
1he find command allovs you to locate tiles and directories vithin the Iinux
tree based upon size, ovner, age, and other criteria. 1he tr command translates and
deletes characters. 1he tee command sends output both to the screen and to a tile.
1he mail command allovs you to send and receive e-mail messages.
6VIW 5US1IONS
1. Which command is used to locate tiles
a. who
b. find
c. tr
d. mail
2. Which command is used to send and receive messages
a. who
b. find
c. tr
d. mail
3. You use to redirect input.
a. >>
b. <
c. >
d. ${...|
4. 1he tile descriptor tor standard error is .
a. 1
b. 0
c. 9
d. 2
3. You use to redirect output and create a nev tile.
a. >>
b. <
c. >
d. ${...|
4
6. You use to redirect output and add data to the end ot a tile.
a. >>
b. <
c. >
d. ${...|
7. 1he option on the tee command allovs you to append to a tile.
a. ~o
b. ~a
c. >
d. >>
8. 1he detault location tor standard input is the .
a. printer
b. hard disk
c. screen
d. keyboard
9. Which is used to pertorm command substitution
a. '...'
b. <
c. >
d. `...`
10. 1he command translates uppercase letters to lovercase letters.
a. tr
b. tee
c. mail
d. find
11. 1he metacharacter preserves all characters except a single quote.
a. \
b. "
c. `
d. '
152 Chapter 4 1he Shell nvIronment
RevIew QuestIons 153
12. 1he metacharacter preserves all characters except the dollar
sign, the single back quote, and the backslash.
a. \
b. "
c. `
d. '
13. 1he metacharacter preserves the character tolloving it.
a. \
b. "
c. `
d. '
14. 1o nest using command substitution, you use the torm.
a. '...'
b. "..."
c. `...`
d. ${...|
13. 1o locate tiles that are 2 kilobytes, you use the command.
a. ls ~l 2k
b. find ~size 2k
c. find ~length 2k
d. find ~size 2c
16. 1o locate tiles ovned by Marge, you use the command.
a. ls ~owner=Marge
b. find ~who Marge
c. find ~owner Marge
d. find ~user Marge
17. 1o convert the letter v to uppercase, you use the command.
a. tr v V
b. tr V v
c. ls v ] tee ~a out.txt
d. tr :upper: :lower:
4
18. 1o redirect standard error ot the pwd command to a tile named Lrror.txt, use the
command.
a. pwd &>2
b. pwd 2>error.lst
c. pwd 2>Error.txt
d. pwd > Error.txt
19. 1o redirect standard output and standard error ot the who command to a tile
named vholist.txt, use the command.
a. who &>l & 2
b. who>>wholist.txt
c. who 2>wholist.txt
d. who &> wholist.txt
20. 1o display the output ot the ls command to the screen and to a tile named
lslisting.txt you use the command.
a. ls ] tr lslisting.txt
b. find ~name lslisting.txt
c. ls ] tee ~a lslisting.dat
d. ls ] tee lslisting.txt
,ANDSON 4ROJC1S
Project 4-1
In this project, you vill reintorce your knovledge ot redirecting input and output. 1he
goal ot this project is to use redirection to alter vhere the input ot a command is com-
ing trom or vhere the output ot a command is going to.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1o redirect output, type who > x.dat, and then press Lnter.
3. 1o redirect and append output, type ls >> x.dat, and then press Lnter.
4. 1o redirect and append output, type pwd >> x.dat, and then press Lnter.
3. 1o redirect and append output, type date >> x.dat, and then press Lnter.
6. 1o redirect and append output, type echo "The end" >> x.dat, and then
press Lnter.
7. 1o display the contents ot the output tile, type cat x.dat [ more, and then
press Lnter.
8. Pecord the output.
,ERHWSR
4VSNIGX
154 Chapter 4 1he Shell nvIronment
Hands-on Projects 155
9. 1o overvrite the output tile previously used by redirecting the output and creat-
ing a nev tile, type echo "Oops" > x.dat, and then press Lnter.
10. 1o display the contents ot the output tile, type cat x.dat, and then press Lnter.
11. Pecord the reason tor ditterence in this output compared vith the output you
recorded in Step 8.
12. 1o redirect standard input, you tirst need to create a tile to vork vith. Create a
tile named unsort.dat vith the tolloving data
3
1
2
13. 1o redirect input, type sort < unsort.dat, and then press Lnter.
14. Pecord the output.
13. 1o redirect input and output, type sort < unsort.dat > sort.dat, and
then press Lnter.
16. 1ype cat unsort.dat, and then press Lnter.
17. Pecord the output.
18. 1ype cat sort.dat, and then press Lnter.
19. Pecord the output.
20. Pecord the reason the tvo previous tiles ditter.
21. Close your vindov, and then log out.
Project 4-2
In this project, you vill reintorce your knovledge ot redirecting standard output and
standard error.1he goal ot this project is to use redirection to alter vhere the output ot
a command and any resulting error messages are sent.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a tile named P4-2.dat.
3. 1o redirect standard output and standard error to ditterent tiles, type
ls P4-2.dat > List.txt 2> ListError.txt, and then press Lnter.
4. Display the contents ot both tiles.
3. Pemove the tile named P4-2.dat, so you can generate an error in the next
command.
6. 1o see vhat happens vhen an error is generated, repeat Step 3.
7. Display the contents ot both tiles.
8. Pecord the output and the reason tor the output.
9. 1o redirect standard output and error to the same tile named both.txt, type
ls P4-2.dat &>both.txt, and then press Lnter.
,ERHWSR
4VSNIGX
4
10. Display the contents ot the tile named both.tt.
11. Pecord the output and the reason tor the output.
12. Close your vindov, and then log out.
Project 4-3
In this project, you vill reintorce your knovledge ot the concept ot pattern matching.
1he goal ot this project is to create several tiles, and then vrite a script to pertorm pat-
tern matching techniques tor the listing ot tiles.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create the tolloving tiles in the same directory pay042004.dat, pay022004.dat,
pay122004.dat, pay042003.dat, pay02004.dat, pay102004.dat,
sales012004.dat, sales0S2004.dat, sales102004.dat, and sales042004.dat. 1he
tiles have a three character name tolloved by a tvo digit month and a tour digit
year.1he tile extension is dat.
3. Create a script named Project4-3 in the 8HOML/bin directory.
4. Iist all tiles beginning vith any letter in the range a-r.
3. Iist all tiles beginning vith an s.
6. Iist all sales tiles that include the year 2004.
7. Iist all pay tiles tor April.
8. Iist all tiles vith a txt extension.
9. Save the script, and then close the editor.
10. Pun the script, record the commands used in Steps 9-12, and then record or print
the script.
11. Close your vindov, and then log out.
Project 4-4
In this project, you vill reintorce your knovledge ot the concepts ot redirection and
pattern matching. 1he goal ot this project is to use the tiles created in Project 4-3, then
vrite a script to pertorm both redirection and use pattern-matching techniques.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named Project4-4 in the 8HOML/bin directory.
3. Iist all tiles beginning vith pay, and then redirect output to a tile named
PayIist.txt.
4. Iist all sales tiles tor August, redirect output to a tile named AugIist.txt, and then
redirect standard error to LrrorIist.txt.
3. Iist all pay tiles vith a .txt extension, and then redirect both standard output and
error to Pay1xtIist.txt.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
156 Chapter 4 1he Shell nvIronment
Hands-on Projects 157
6. Iist all tiles beginning in the range ot a-z, and then redirect both standard out-
put and error to azIist.txt.
7. Save the script, and then close the editor.
8. Pun the script, record the commands used in Steps 3-6, record the command
used, and then record or print the script.
9. Close your vindov, and then log out.
Project 4-5
In this project, you vill reintorce your knovledge ot the concept ot quoting. 1he goal
ot this project is to have you vrite a script that quotes metacharacters, and then redirect
that output to a tile. By combining the quoting and redirection in one project, you vill
see the importance ot quoting. (Hint It you don`t put the correct quoting characters in
the correct place, you could end up vith errors.,
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named Project4-S in the 8HOML/bin directory.
3. Insert the tolloving lines ot code
echo "This file has single guotes 'see'." > echolist.txt
echo "I've earned '$'500.00 "in sales this week." >> echolist.txt
echo "James' " '$'Money'$' "list" >> echolist.txt
echo The prompt on some systems has this symbol \>. >> echolist.txt
4. Save the script, and then close the editor.
3. Pun the script, record the commands used in Step 3, and then record or print
the script.
6. Close your vindov, and then log out.
Project 4-6
In this project, you vill reintorce your knovledge ot expansion.1he goal ot this project
is to help you understand the concepts ot tilde expansion, parameter or variable expansion,
and command substitution.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1o display your current vorking directory using tilde expansion, type echo -+,
and then press Lnter.
3. 1o display your previous vorking directory using tilde expansion, type echo --,
and then press Lnter.
4. 1o use tilde expansion to change to your home directory, type cd -, and then
press Lnter.
3. 1o set a value to be used vith parameter expansion, type Value="ABC123", and
then press Lnter.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
4
6. 1o display the last three character positions, type echo ${Value:3:3}, and then
press Lnter.
7. 1o display the last (sixth, character position, type echo ${Value:5:1}, and
then press Lnter.
8. 1o display the length ot the variable Value, type echo ${#Value}, and then
press Lnter.
9. 1o use command substitution to set a variable equal to the output ot the previous
command, type len=${echo ${#Value}}, and then press Lnter.
10. Display the contents ot the variable named len.
11. 1o use command substitution to set a variable named passvord equal to the last
three characters in the value, type password=${echo ${Value:3:3}}, and
then press Lnter.
12. Display the contents ot the variable named passvord.
13. Close your vindov, and then log out.
Project 4-7
1he goal ot this project is to help reintorce your understanding ot the find command.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. 1o locate directories and redirect the output to a tile, type find -type d >
dirlist.txt, and then press Lnter.
3. 1o locate tiles that are 3k (kilobyte, in size or larger and redirect the output, type
find -size 3k > ThreeK.txt, and then press Lnter.
4. 1o locate tiles that haven`t been moditied in seven days and redirect the output to
a tile, type find -mtime 7 > SevenDays.txt, and then press Lnter.
3. 1o locate tiles that haven`t been moditied in three days and that are 1k in size,
type find -type f -size 1k -mtime 3, and then press Lnter.
6. 1o locate tiles that haven`t been moditied in 30 days, that are 10k in size, that are
ovned by your username, and then to redirect standard output and error to a tile,
type find -type f -size 10k -mtime 30 -user username &>
findlist.txt, and then press Lnter. Peplace username vith your ovn user
name.
7. Close your vindov, and then log out.
Project 4-8
1he goal ot this project is to help reintorce your understanding ot the tee command.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named Project4-8 in the 8HOML/bin directory.
3. Pun the correct command to display a long listing to the screen, and then place
the results ot the long listing in a tile named Project4-8list.tt.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
158 Chapter 4 1he Shell nvIronment
Case Projects 159
4. Pun the correct command to display the currently logged in users to the screen,
and then append the results to a tile named Project4-8list.tt.
3. Pun the correct command to tind only tiles in the current directory and display
them on the screen, and then append the results to a tile named Project4-8list.tt.
6. Pun the correct command to tind only tiles in the current directory that begin
vith letters in the range a-z and display them on the screen, and then append
the results to a tile named Project4-8list.tt.
7. Save the script and then close the editor.
8. Pun the script, record the command used, and then record or print the script.
9. Close your vindov, and then log out.
'AS 4ROJC1S
Case 4-1
You have been hired by 1MI to create a shell script using pattern-matching techniques.
1he payroll department needs the tolloving tiles created and then placed in the Payroll
directory that you created in Case 2-1
jan07.dat dec04.dat jul04.dat teb06.dat apr06.dat dec06.dat
jan02.dat teb14.txt jun06.dat teb16.dat aug06.txt jun04.dat
jan03.dat jul04.txt jul13.txt teb26.dat may06.txt jun06.txt
oct27.txt teb07.dat dec07.dat apr28.dat mar06.dat apr09.txt
Because the I1 statt has a limited knovledge ot the Iinux operating system, they vant
you to help them pertorm the tolloving tasks. Pun the commands at the command line
to make sure you get them to vork properly. Once they are correct, place these com-
mands in a shell script. 1hen, test and run the script.
1he script must include a Iinux statement tor each step belov
1. Display all tiles vith an extension ot dat.
2. Display only tiles tor anuary.
3. Display all tiles that begin vith a j and have an extension ot dat.
4. Display all tiles only tor the seventh ot every month.
3. Display all tiles that begin vith the letter j or the letter d.
'EWI
4VSNIGX
4
Case 4-2
enny`s Motorcycle and Sidecar Shop has a Iinux system used to run their main sales
shop and tvo satellite sales ottices. Pecently, their Iinux System Administrator lett, and
they need you to vrite a script tor them. 1he script must pertorm the tolloving and
redirect output and errors to one or more tiles in your home directory
lind all tiles that are at least 10 kilobytes.
lind all tiles ovned by root that are 100 kilobytes in length.
Lse the man pages to construct the correct command to locate only tiles
vith the permissions ot read, vrite, and execute tor all tiles ovned by root.
Display the contents ot the output tile(s,, and then translate all lovercase letters
to uppercase.
Print the output tile(s, vithin the script.
'EWI
4VSNIGX
160 Chapter 4 1he Shell nvIronment
161
',%48)6

7,)00 7'6-48 463+6%11-2+


'32')487
-RXLMWGLETXIV]SY[MPP
9RHIVWXERHXLIWIUYIRXMEPJPS[SJWLIPPWGVMTXMRK
1EREKIWLIPPWGVMTXW
9RHIVWXERHXLIFEWMGGSQTSRIRXWSJEWLIPPWGVMTX
9RHIVWXERHTEVEQIXIVW
'VIEXIMRXIVEGXMZIWGVMTXW
9RHIVWXERHHIFYKKMRK
8
his chapter gives you an overviev ot shell script programming.You need
to understand the tlov ot shell scripting in order to ettectively vrite shell
scripts. You vill learn hov to manage shell scripts, vhich entails changing
the permissions on a script to allov you to execute it by simply entering the
script name. You vill also learn hov the shell executes a script. By placing
the script in a directory vhich is on the search path, you vill be able to run
the script trom any directory location.You vill learn the basic components
ot a script vhich include adding comments to a script and adding a usage
clause vhich indicates to the user hov to run the script.Alloving your script
to accept values trom the command line or interact vith the user vill also
be discussed. linally, you vill learn hov to debug and troubleshoot your
script to handle any execution errors you may run into.
9NDRS1ANDING 1H 7QUN1IAL *LOW Of 7HLL 7CRIP1ING
Shell scripts allov you to combine programming logic vith operating system commands
to automate parts ot your job.1he term sequential, as it applies to shell scripting, means
one command executes at a time. All programming languages execute their statements
in sequential order.You can alter this order vith decision statements, looping structures,
and tunctions. 1hese concepts are discussed in later chapters.
Iet`s look at an example taken trom most everyone`s daygetting ready tor school or
vork. 1his overall task can be set up in a series ot sequential steps in pseudocode. As an
example, here is the list ot steps that one could use to get ready tor school or vork
1. lurn aiarm .io.k off.
2. et out of |eo.
'. :houer ano .iean up.
4. Dress.
. Lat |reakfast.
. Prush teeth.
7. Dri:e to s.hooi or uork.
Granted, some steps in this list can be done in a ditterent order.You might say that you eat
breaktast betore you shover and dress. Or, you may be late so you skip eating breaktast
and brushing your teeth. Hovever, you must do some ot these steps prior to others.You
must get out ot bed betore you dress or even drive to school or vork. And, it you
complete the list ot steps in the order shovn, then you have a routine, or program, tor
getting ready tor school or vork everyday.
1he getting-ready-tor-school-or-vork routine parallels the concept ot a sequential tlov
ot a shell script. In the above example, each ot the individual steps is equal to a command.
1he collective steps are considered the program. In shell scripts like the getting-ready-
tor-school-or-vork program, some commands may be executed betore other commands,
and there are some commands that must be executed betore others.
A shell scripL is a proram.
In order to help understand the sequential tlov ot shell scripting, you vill create a simple
three-line shell script.1he tolloving steps are the pseudocode tor the shell script.As you may
8MT
162 Chapter 5 Shell ScrIpt ProgrammIng Concepts
UnderstandIng the SequentIal flow of Shell ScrIptIng 163
already knov, pseudocode allovs you to concentrate on the logic ot your program instead
ot being concerned about the specitic syntax. Peviev the tolloving pseudocode
1. Change directory locations to root.
2. Pun a listing on the directory.
3. Display the current vorking directory.
Next you vill turn this pseudocode into a shell script.
1o create a shell script fron pseudocode:
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. 1o change to the bin directory, type cdbin and then press Lnter.
3. 1o create the shell script vith the name IistPoot, type viListRoot, and
then press Lnter.
4. 1ype i to insert a line ot text. 1he text INSLP1appears at the bottom
ot the vindov.
3. 1o mirror the pseudocode statements, insert the tolloving lines ot code to
the IistPoot script
cd /
ls
pwd
6. In order to save the script, press Lsc, type :wg!, and then press Lnter.
7. In order to execute the IistPoot script, type bash ListRoot, and then
press Lnter. 1he shell script executes and pertorms the statements you added
in Step 4specitically, changes to the root directory, pertorms a directory
listing, and then displays the present, or current, vorking directory. ligure 3-1
shovs the IistPoot script and its execution.
8. Close your vindov, and then log out.
When you create a shell script, you must arrange the commands in a logical order. 1he
logical order depends upon the task you are trying to accomplish. In the IistPoot script,
it you placed the pwd command betore the ls command, the order ot processing vould
change. In this case, the ls vould execute last. Although this is a minor change in this
shell script, in some cases, it you place the commands out ot order, it can create unexpected
results.1ake tor example, a shell script that redirects output to a tile.
You learned in ChapLer 4 Lhe dierence beLween usin a sinle reaLer-Lhan
symbol and Lwo reaLer-Lhan symbols Lo redirecL ouLpuL. 1he sinle reaLer-
Lhan symbol overwriLes Lhe currenL conLenLs o Lhe ile. Usin Lwo reaLer-Lhan
symbols appends Lo a ile.
5
In the tolloving sequence ot commands, the tirst echo command is redirecting the text
output to a tile named output.txt. Any previous data is overvritten. 1he next tvo
echo statements are appending to the same tilename.
echo "output" > output.txt
echo "more output" >> output.txt
echo "even more output" >> output.txt
What vould happen it you placed the tirst line at the end ot the list ot commands In
other vords, it you used the tolloving code instead ot the previous code
echo "more output" >> output.txt
echo "even more output" >> output.txt
echo "output" > output.txt
1he ansver to this question is that any previous data in the tile vould be lost. Although
the tirst tvo commands are appending output, thus preserving any previous data in the
tile, the last statement is using a single greater-than symbol to overvrite the tile, thus
resulting in any prior data being lost. What you vill have in the tile, atter the last state-
ment is executed, is simply the text output in the tilenothing else. 1his is a problem
it you vant to keep any existing data.
1he best vay to ensure the correctness ot your shell script is to vrite the logic on paper
as pseudocode. 1hen, it possible, have your instructor reviev it. Next, convert the
pseudocode statements into commands using an appropriate Iinux editor. linally, run
the shell script.
fIgure 5-1 1he LisLRooL scripL
164 Chapter 5 Shell ScrIpt ProgrammIng Concepts
ManagIng Shell ScrIpts 165
1ANAGING 7HLL 7CRIP1S
In this section, you vill learn hov to manage shell scripts. When you manage a shell
script, you are making the script executable in a location vhere the users vill be able to
run it. Managing shell scripts involves the tolloving
Moditication ot a shell script`s tile access permission
Placement ot shell scripts
ModIfIcatIon of the fIle Access PermIssIon of a Shell ScrIpt
As you have learned, you can execute a shell script by entering the shell`s name, such as
bash, tolloved by the script`s name. lor example, to execute a shell script named paychecks,
you enter bashpaychecks at the command line. Hovever, it you use a script trequently,
there is a method that is more streamlined and that is videly used among programmers.
Instead ot entering the name ot the shell (in this case bash, you can modity the permissions
ot your script so you can execute it by simply entering the script`s name. 1he chmod
command allovs you to modity the tile access permission on a tile or directory. Pecall that
you learned about permissions in Chapter 2.1he permissions are read, vrite, and execute
tor the user vho ovns the tile, the group ovnership ot the tile, and others. When a
tile is tirst created, it has certain detault permissions. lor nonroot users, the detault tile
permissions are read and vrite tor the user vho ovns the tile as vell as the group
membership on the tile, and just read tor others. lor the root user, the permissions are
read and vrite tor the ovner and read tor the group and others. 1he chmod command
takes the tolloving general torm
chmod ugo +~= rwx f11ename
In this syntax, u represents the user or ovner ot the tile, g represents the group permissions
on the tile, and the o represents the other users. 1he + sign means to add a permission to
1o nodify the eecute pernissions of a file using letter notation so you can
sinply enter the scripts nane:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation
vindov.
2. Move ListRoot to the -/bin directory.
3. Change directory locations to the -/bin directory.
5
4. 1ype chmod ugo+x ListRoot, and then press Lnter. 1he prompt returns.
3. 1o verity that the execute permission has been set, type ls ~l ListRoot,
and then press Lnter. Notice that the execute permission has been added.
6. Pun the script by simply entering ListRoot. Notice that the command
executes just by entering the script`s name.
7. Close your vindov, and then log out.
Nov that you knov hov to modity the permissions ot a script in order to make it
executable, you vill utilize this concept in subsequent exercises and labs as vell as
on the job.
Another method ot changing permissions vith the chmod command is to use numbers
to represent the permissions tor the user, group, and other users. 1his method takes the
general torm
chmodnnn f11ename
Here, n represents a number trom 0 to 7. Lach n represents the permission number tor
the user ovner, group, and other users.1able 3-1 shovs the permissions and numbers to
vhich they reter.
1he best vay to use this table is to look tor the permission you vant and then look to the
right to tind the appropriate number you need.1he three permission columns represent a
4, 2, and 1 tor read (r,, vrite (w,, and execute (x,, respectively tor the user ovner, group,
and other users.You add up the numbers tor the permissions you vant. lor example, it you
vant read-only, you simply need 4 tor the permission. It you vant read and vrite, you
vould add 4 and 2 to get the number 6. It you vant read, vrite and execute, you add up
4, 2, and 1 to get the number 7.
PermIssIons Number
~~~ 0
~~x 1
~w~ 2
~wx 3
r~~ 4
r~x 5
rw~ 6
rwx 7
1able 5-1 Permission numbers or Lhe chmod command
166 Chapter 5 Shell ScrIpt ProgrammIng Concepts
ManagIng Shell ScrIpts 167
So, it a tile named program1 needed to have read, vrite and execute tor the user ovner,
read and execute permissions tor the group, and no permissions tor all others, you vould
enter chmod 750 programl.
Next you vill pertorm an activity using the chmod command vith the number notation.
1he end result is the same as the letter notation ot the chmod commandto be able to
execute a script by entering just the name on the command line. Hovever, you can use
the chmod command to modity other permissions.
1o nodify the eecute pernissions of a file using nunber notation:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation
vindov.
2. Change to the bin directory.
3. Create a shell script that displays the current date and a list ot users logged on
the system. (Hint use the date command tolloved by the who command.,
Be sure to save the script vith the name LoggedOn in the bin subdirectory
ot your home directory, and then close vi.
4. 1he current permissions are rw~ tor user ovner and group and r~~ tor all
others.1o add execute permission tor all three permission sets, type chmod 775
LoggedOn, and then press Lnter. By using 773, you are setting the permissions
to rwx tor the user ovner and group and r~x tor all others.You are only
adding execute.
3. 1o verity the permissions type ls -l LoggedOn, and then press Lnter.
6. Lxecute the script named LoggedOn.
7. Close your vindov, and then log out.
Some users tind the number method easier to enter trom the keyboard once they
understand its methodology. As a user vriting shell scripts, you need to understand both
methods. One reason is that there are process startup scripts located in the etcrc.dinit.d
directory that use both methods.You vill need to understand the startup scripts in order to
troubleshoot the Iinux system. lor example, it you execute the command grep chmod *
in the etcrc.dinit.d directory you vill see scripts that use either method. 1he grep
command allovs you to search tor text in tiles and vill be covered in Chapter 10. 1he
command given above searches tor the text chmod in all tiles.
Lxercise cauLion when usin Lhe chmod command. You don'L wanL Lo inadver-
LenLly ive roup owners or oLher users excess permissions. For example, i a
ile named ileA.LxL is creaLed, iL would have deaulL permissions o rw~rw~~
r~~. l you execuLed chmod 777 fileA.txt, Lhen everyone on Lhe sys-
Lem would have all permissions, includin wriLe. 1his would ive anyone access
Lo modiy or even deleLe ileA.LxL wheLher you inLended Lhis or noL.
5
Placement of Shell ScrIpts
When you create a script or vant to tind an existing script, it`s a good idea to understand
hov the shell locates scripts that are to be executed. Here`s hov it vorks. It you enter a
command or script name using its tull path, the shell attempts to locate the command in
the specitied directory. Say you entered the tolloving command at the shell prompt
/scripts/scriptl
Assuming the script is executable, hov does the shell knov hov to locate the script
named script1 in order to execute it Simply put, the shell attempts to locate the shell
script named script1 in the scripts directory because you told it to look there vhen
you entered the tull path on the command line. It the shell script is not present, the
shell generates an error message indicating the shell script tile cannot be tound.
Nov, it you enter the command or script name using the partial path instead ot the
tull path, the shell attempts to locate the directory the script is in a little ditterently.
Say you executed the same script as above but lett ott the root symbol and directory
location as tollovs
scriptl
Hov does the shell knov in vhich directory the script is located 1he shell searches
each element ot the PATH shell variable tor a directory containing the script tile. It
the directory is located that houses script1, the tile is executed. Othervise, an error
is displayed. ligure 3-2 displays the contents ot the PATH variable.1he command used
to display the contents ot the PATH variable is echo $PATH. 1his variable is otten
called the search path.
fIgure 5-2 ConLenLs o Lhe PATH shell variable
Your PATH may dier rom
whaL is shown
168 Chapter 5 Shell ScrIpt ProgrammIng Concepts
ManagIng Shell ScrIpts 169
In this example, you can see that there are six directories on the search path.Your actual
search path may be ditterent it a System Administrator changed the setting ot the PATH
variable. Changing the PATH is typically done in one ot the startup tiles tor the user
account. In ligure 3-3 you can see the tirst directory listed is searched tirst. 1he next
directory in the list is searched only it the script tile is not tound in the tirst directory.
1his process continues until the directory containing the tile is tound or the last directory
is reached. It the shell cannot locate the script in any ot the directories listed, then an error
appears indicating the shell cannot tind the script.
You can also display Lhe conLenLs o Lhe PATH shell variable usin Lhe env
command. 1his command displays all variables or a iven user accounL. 1he
imporLanL Lhin Lo noLe here is LhaL Lhis command shows a colon separaLin
each direcLory or Lhe PATH variable.
1he main reason tor the search path is to make your job easier. It is much easier on you,
the Iinux user, it you can just enter the script name vithout having to enter the directory
in vhich it is located. 1here is less to enter at the keyboard, resulting in tever typos and
errors. In order to run a shell script vithout using the tull path name, you tollov one ot
tvo methods. lirst, you can create a directory, place the shell scripts in the directory, and
then add the directory to the search path. 1his method is usetul vhen you have a shell
script that needs to be used by many users or vhen you have a set ot scripts you vant to
test. Next, you vill see hov this method vorks by creating a directory named testing vhere
you vill later place shell scripts that you are testing and don`t vant other users to access.
1o create a directory and place it on the search path:
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a directory in your home directory named testing.
3. 1ype PATH=$PATH:$HOME/testing, and then press Lnter. 1his command
appends the current path, $PATH, vith the directory, $HOME/testing. 1he
text PATH= sets the path.
8MT
usr/kerberos/bin usr/local/bin usr/bin /bin /usr/X11R6/bin /home/Loddm/bin
Search
order: 1
sL
2
nd
3
rd
4
Lh
lasL
... ...
fIgure 5-3 Search order o Lhe search paLh
5
4. Change your current directory to the $HOME/testing directory.
3. Lse the vi editor to create a shell script, named display_hi that displays
the text Hi.
6. Save the script, and then close vi.
7. Change to the $HOME directory to demonstrate the search path is used.
8. 1ype bash display_hi. 1he text Hi should appear on the screen.
9. Close your vindov, and then log out.
Another method tor running the script vithout using the tull path name is to place your
shell script in one ot the directories listed in the current search path. When you install
the Iinux operating system, there are a tev directories that are used tor the purpose ot
customization. lor example, you can place your scripts in the usrlocalbin directory
or the $HOME/bin directory because both ot these directories are on the search path.
You can also place your scripts in the $HOME/bin directory as you have already done
in previous exercises in this chapter. Lither method vorks tine, but it you vant to sep-
arate your scripts tor testing, you should create a separate directory and place the direc-
tory name in the search path.
1he namin o scripLs should be meaninul and unique. 1he scripL name musL
noL duplicaLe Lhe name o some oLher execuLable in Lhe user's currenL paLh
unless iL will always be run usin Lhe ull paLh name or an appropriaLe parLial
paLh name.
9NDRS1ANDING 1H &ASIC 'OMPONN1S Of A 7HLL 7CRIP1
In this section, you vill learn about the basic components ot a shell script.All shell scripts
can be broken dovn into the tolloving list ot components
Command interpreters
Comments
Variables
SpecIfyIng the Command Interpreter
You should place a statement that reters to the command interpreter that is being
used in the very tirst line ot your script. Pemember trom Chapter 1 that several shells,
or command interpreters, exist in the Iinux environment. Lach shell has its ovn syntax
rules, so commands that vork in one script may not vork in another. It you have
multiple scripts that use ditterent shells, you should place statements reterencing the
command interpreters at the beginning ot each script. 1he advantage ot specitying
the command, or shell, interpreter in your program is that you ensure that later statements
execute in the shell you vant.
8MT
170 Chapter 5 Shell ScrIpt ProgrammIng Concepts
UnderstandIng the asIc Components of a Shell ScrIpt 171
1o specity the shell that is used to process subsequent commands in your script, place
the statement #!, tolloved by the tull path to the shell, as the very tirst line ot your
script. Consider the tolloving example
#!/bin/bash
# Comments
pwd
1he tirst line reterences the command interpreter, the second includes any additional
comments, and tinally the third line contains the command statements.
1able 3-2 provides a list ot the common Iinux shells and their tull paths.
You can use Lhe which command Lo deLermine Lhe ull paLh o Lhe shells,
or any commands. For example, which bash displays Lhe ull paLh o Lhe
bash shell.
Consider the script named MAIN shovn in ligure 3-4. MAIN is vritten in the bash
shell. Hovever, it reterences other scripts vritten in ditterent shells. Lach ot these scripts
reterences the appropriate shell to be used tor processing the commands vithin it. As
each script completes, it returns to the MAIN script.1hen, the next command or script
in sequence executes.
Comments
Comments are placed in shell scripts so you and others understand vhat the programmer
vas thinking vhen he created the script. Anyone vho has vrite permission to the script
can place comments in it. 1his vay, vhen the time comes tor moditication, you have a
complete understanding ot the programming that has already taken place. Accurate
comments are essential to the programming process. Inaccurate comments are vorse than
no comments at all because they lead you to think one vay vhen the program is doing
something completely ditterent.You implement or place comments by using the # symbol
anyvhere on a line. Commands or text tolloving the # symbol vill not be executed.
8MT
Shell Path
8ash /bin/bash
Ksh /usr/bin/ksh
Sh /bin/sh
Csh /bin/csh
1able 5-2 Full paLhs o common Linux shells
5
1he use ot # tor comments causes the shell to ignore the line.You can place comments
prior to a command to cause the shell to ignore the command.1his can be usetul it you
are testing nev statements in a script but are not sure it these statements vill vork as
you`ve planned. lor example, #pwd causes the shell to treat the pwd command as part
ot the comment text tolloving the # symbol. It the # symbol vere removed, the pwd
command vould execute normally.
In general, there should be a comment section at the beginning ot every script so it is
the tirst thing someone opening your script sees. Comments should contain the author
ot the script, a description ot the script, the name and version number ot the script,
required parameters, the date moditied, and a description ot the moditication. ligure 3-3
shovs a script that uses comments. Note this is only a partial script.
At times, you may vant to place comments close to actual code statements. In the
tolloving example, a comment is placed prior to each statement indicating vhat the
next statement vill do.
# Computes the new salary for the sales representatives
{{Salary=$Salary+$Bonus||
# Displays the output to the screen
echo "Salary for $SalesPerson is $Salary and bonus amount is $Bonus"
#!/bin/bash
# Script Name: MAIN
shscript
# bash commands
follow
kshscript
cshscript
#!/bin/csh
# csh commands
follow
#!/bin/ksh
# ksh commands
follow
#!/bin/sh
# sh commands
follow
fIgure 5-4 Speciyin command inLerpreLers in scripLs
172 Chapter 5 Shell ScrIpt ProgrammIng Concepts
UnderstandIng the asIc Components of a Shell ScrIpt 173
In this next example, comments are placed to the right ot commands. Lach command
executes normally because the # symbol tollovs, rather than pre.eoes the command.You
see this approach used otten in shell scripts because it saves space in the script tile and
places the comment closer to the actual command it reterences.
pwd # Prints current directory
ls ~l # Displays a long listing
Although time consuming, the use ot comments can reduce the time it takes to make
moditications to the script. Lven it you are the only one moditying the script, you should
use comments. It`s not unheard ot tor experienced System Administrators or programmers
to sometimes torget vhy they vrote something a certain vay vhen they created the script.
Although placing comments in your script may take some time nov, it vill save a lot ot
time later vhen you need to remember vhy you did something.
VarIables
A variable is used to represent data. It is composed ot the variable name and the data, or
contents. lor example, the variable name x may have the number 3 as its data. 1he
variable can be assigned by setting x to 3 as in the statement x=5.1he contents ot a variable
are held in memory vhile in use.You can think ot a variable as a cell in a spreadsheet.
A variable is someLimes called a ield or a daLa name. 1o reer Lo Lhe conLenLs o
a variable in Lhe bash shell scripL, you precede Lhe variable name wiLh a dollar
sin, $, as in $NetPay. For example, Lhe command echo $NetPay displays
Lhe conLenLs o Lhe variable named NeLPay.
fIgure 5-5 Use o commenLs in a scripL
5
Programmers try to assign variable names that describe the data they contain. lor example,
it the data contains a net pay amount, then a descriptive name assignment vould be NetPay
or NL1_PAY. Programmers also make the variable names readable. lor example, the
variable named inventoryquantityonhand is not very easy to read. Lntortunately, most
programming languages, including shell scripts, do not allov you to place a space or a
hyphen betveen the vords in the variable name. 1he variable names Net Pay and
Net-Pay are not alloved. So, a programmer places underscores betveen the vords ot the
name, uses common abbreviations, or capitalizes the tirst letter ot each vord to make
the variable easier to read vhen revieving a script. 1hus, the tolloving variable names
vould be acceptable InventoryQuantityOnHand, InvQtyOnHand, QuantityOnHand,
or Qty_On_Hand.
You can also indicate the type ot data that a variable can contain as vell as the size ot
the data. lor example, it you have a variable such as NetPay and you knov it should
contain only numbers, you can indicate that NetPay is a numeric or an integer data type.
lor variables that only contain characters, you detine them as a character string. When
you detine the size ot the variable, you need to make the size large enough to hold all
ot the data. lor example, it you detine a character tield to be tive characters, and you try
to store data vith more than tive characters, the data vould be truncated on the right.
Variable declaration is the act ot specitically detining the variable name and type. When
you declare a variable, memory space is allocated tor the variable`s name and type. It is a good
idea to detine your variables near the beginning ot your script or just prior to using them
in a script.1here are tvo commands that allov you to declare a variable in a script.1hey are
the declare command and the typeset command. 1heir tunctions are identical. lor
example, to declare a variable as an integer tor arithmetic evaluation and another variable as
integer and read-only, you enter the tolloving
declare ~i TotalSales
declare ~i ~r InterestRate
Initialization is the act ot setting a variable to a beginning value. Although not
required, it is advisable to set your variables to initial values so you knov vhat they
contain prior to using them. In the case ot setting integer variables, you vill most likely
set your initial values to zero, tor example, NetPay=0. You can either initialize your
variable in an initialization section at the beginning ot your script or in the script prior
to using the variable.
8MT
174 Chapter 5 Shell ScrIpt ProgrammIng Concepts
UnderstandIng Parameters 175
A variable LhaL has been iniLialized, or seL, can be unseL wiLh Lhe shell unset
command. For example, Lo unseL Lhe variable named NonLhlySales LhaL has
previously been seL Lo a value, you enLer unsetMonthlySales.
Next you vill create a script that contains comments, variable declarations, and initialization
statements to turther your understanding ot these topics.
1o understand hov to inplenent connents, variable declarations, and
initialization statenents in a script:
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named BasicConponents in the $HOME/bin directory.
3. Insert the tolloving lines ot code to initialize the shell interpreter, add comments,
declare and set a variable, and display a variable`s contents. (^ote put your name
in place ot our_name and today`s date in place ot tooa`s_oate,
#!/bin/bash
# Author: ]SYVCREQI
# Date: XSHE]WCHEXI
declare SalesRegion
SalesRegion="Eastern"
echo "The sales region is:" $SalesRegion
4. Make sure you save the script, close vi, and change permissions so you can
execute the script by name.
3. Lxecute the script.1he script displays 1he sales region is Lastern on the screen.
6. Close your vindov and then log out.
9NDRS1ANDING 4ARAM1RS
It is important to understand parameters because they allov you to provide a script
vith data. 1his allovs you to make your scripts much more tlexible because you can
vary the data that goes into the script. Also, parameters give you intormation such as
the status ot a statement or the number ot parameters entered. A paraneter is a name,
number, or special character that stores a value. A parameter is considered to be set it
it has a value and can be set to a number, letters, or the null value. Null means the
variable is set to no value.
1here are tvo types ot parameters used by the shell
Positional parameters
Special parameters
8MT
5
PosItIonal Parameters
You can make a shell script more tlexible using positional parameters to apply values
vithin your script.1he parameters are called positionalbecause they reter to the numeric
position ot the value in the list that tollovs the script`s name. Once the values are given
to the script, you can use these values vithin the script itselt.You use positional parameters
by entering the shell script name tolloved by multiple values on the command line. 1he
general torm tor using positional parameters is
scr1t~name va1ue1 va1ue2 va1ue2.va1ue9
1his is vhere va1ue1, va1ue2, va1ue2, and so torth are positional values given, or
passed, to the shell script. 1he positional parameters are called by number1, 2, 3 and
so on, and respectively represent va1ue1, va1ue2, va1ue2, through va1ue9.
You will learn how Lo pass more Lhan nine parameLers usin addiLional com-
mands laLer in Lhis chapLer.
It you vant to reter to the contents ot a parameter, you precede the parameter vith a
dollar sign ($, tolloved by its positional number. So, the positional parameter $l receives
the value specitied as va1ue1. 1he positional parameter $2 receives the value specitied
as va1ue2. 1he name ot successive parameters is incremented by one until you reach
$9. 1he $0 parameter takes the value ot the actual script name itselt.
You cannoL use $0 or passin values Lo Lhe scripL.
Iook at the tolloving single line shell script named display_it belov
echo $l $2
1he display_it shell script displays tvo positional parameters in this example. 1he
programmer does not knov vhat the data is at the time the script is vritten.1hat is vhat
makes positional parameters so tlexible. 1he programmer does need to knov hov many
parameters to account tor.1o enter the values tor this shell script, you enter the tolloving
display_it a b
1he tirst value, a, is passed to the script as $l. 1he second value, b, is passed to the
script as $2.When executed, this shell script displays the values a and b on the screen.
ligure 3-6 otters turther explanation ot this example.
8MT
8MT
176 Chapter 5 Shell ScrIpt ProgrammIng Concepts
UnderstandIng Parameters 177
1he benetit ot using positional parameters is that you are able to vrite scripts that reter
to parameters regardless ot the value.1his is a povertul teature ot shell scripting.You can
give a script many values and reter to the positional parameter name to get the actual
value.You could rerun the previous script as display_itTheEnd to display the text
1he and Lnd on the screen.1his is just an example.You could execute the script to
display any tvo values as long as you separated them on the command line by a space.
You can also use positional parameters in conjunction vith commands. lor example, you
can create a script to display the contents ot a directory and pass the directory name as a
positional parameter on the command line. 1he tolloving code demonstrates hov you
can modity the IistPoot script to accept any directory as the tirst positional parameter.
cd $l
ls
pwd
lor example, to execute this script and pass the tmp directory to it, you enter
ListRoot /tmp. 1he tirst positional parameter is tmp. 1hus, the script changes
directory locations to tmp, displays a listing ot that directory, and then displays the
present vorking directory.
1he shell knows when one value ends and Lhe oLher beins by usin Lhe builLin
variable named IFS, which sLands or lnLernal Field SeparaLor. lL is seL Lo
space, Lab, and newline and uses Lhese as deaulL separaLors. So, by enLerin
display_it The End on Lhe command line, Lhe shell looks or eiLher a
space, Lab, or newline Lo delimiL each value. 1haL's why "1he" seLs Lo $1 and
"Lnd" seLs Lo $2.
Next, you vill use your knovledge ot expression trom Chapter 3 to create a script that
adds any tvo numbers passed to it.
8MT
echo $1 $2
display_it a b
$0 $1 $2
fIgure 5-6 UndersLandin posiLional parameLers
PosiLional parameLer names
ConLenLs o Lhe sinle line shell scripL named display_iL
PosiLional parameLers are separaLed by a space; addiLional posiLional
parameLers Lake on successive names, such as $3, $4, $5, $6, and so on
WhaL is enLered on Lhe command line
5
1o create a script that accepts and suns tvo positional paraneters:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation
vindov.
2. Change to the $HOME/bin directory.
3. Open the vi editor.
4. 1ype the tolloving lines ot code to create a variable named Sum1 that is the
sum ot tvo positional parameters, and then display the Sum1 on the screen
{{Sum1 = $1 + $2}}
echo $Sum1
3. Save the script as Add1hen, and then exit vi.
6. 1o make it executable, type chmod ugo+x AddThem, and then press Lnter.
7. 1o execute the script, type AddThem 10 5, and then press Lnter. 1he sum
ot 13 is displayed.
8. Perun the script and pass the values 300 and 200 respectively. 1he sum ot 700
is displayed.
9. Close your vindov, and then log out.
Next, you need to understand vhat happens vhen you have more than nine positional
parameters that you vant to pass to a shell script.1o accomplish this you use the shift
command. 1he shift command allovs you to use more values in the shell by shitting
them around. 1he general torm is
shift n
1his is vhere n is a number that indicates hov many positional parameters to shitt.1ake
a look at the tolloving shell script named Shitt1hem
echo $l $2 $3 $4 $5 $6 $7 $8 $9
shift l
echo $l $2 $3 $4 $5 $6 $7 $8 $9
It you executed the script as tollovs
ShiftThem l 2 3 4 5 6 7 8 9 l0
1he output vould be
l 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9 l0
ligure 3-7 shovs the tlov ot the shift command in action.
178 Chapter 5 Shell ScrIpt ProgrammIng Concepts
UnderstandIng Parameters 179
ligure 3-8 displays the script called Shitt1hem along vith the output ot its execution.
What vould happen it you shitted the positional parameters more than one number, tor
instance, three positions 1he ansver is that the positional parameters shitt the number you
specity, or three in this case. ligure 3-9 shovs a breakdovn ot shitting three parameters.
fIgure 5-8 1he ShiL1hem scripL and Lhe ouLpuL o iLs execuLion
echo $1 $2 $3 $4 $5 $6 $7 $8 $9
1 2 3 4 5 6 7 8 9 10
Lcho sLaLemenL displays Lhe values 1 Lhrouh 9
echo $1 $2 $3 $4 $5 $6 $7 $8 $9
1 2 3 4 5 6 7 8 9 10
shiL 1
Lcho sLaLemenL displays Lhe values 2 Lhrouh 10
fIgure 5-7 An explanaLion o Lhe shift command
CannoL be used yeL because you are
limiLed Lo nine posiLional parameLers
ParameLers are shiLed, so Lhe irsL value
drops o
Causes Lhe daLa Lo be shiLed
one posiLion
5
Iet`s take a look at a practical implementation using the shift command. Imagine you
need to add together 10 donations raised at a charity auction. Because you can only pass
nine arguments to a script at one time, you have to shitt the values to ditterent positional
parameters. 1he script, named DonatedSum, tollovs
{{DonatedSum=$l + $2 + $3 + $4 + $5 + $6 + $7 + $8 + $9 ||
shift 9
{{DonatedSum=$DonatedSum + $l||
echo $DonatedSum
In this sample code, the variable named DonatedSum is equal to the summation ot the
tirst nine positional parameters. Next, the shift 9 command shitts the parameters
to the right nine positions so the nev value ot $l becomes the 10
XL
parameter. 1he
parameter $l no longer contains the tirst value. ligure 3-10 shovs the DonatedSum
script vith output. 1he variable sum contains the summation ot the values ot all ot
the positional parameters.
Next you vill create a script that uses shitting positional parameters.
1o create a script that shifts positional paraneters:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation
vindov.
2. Change to the $HOME/bin directory.
3. Open the vi editor.
$1 $2 $3 $4 $5 $6 $7 $8 $9
1 2 3 4 5 6 7 8 9 10 11 12
shift 3
$1 $2 $3 $4 $5 $6 $7 $8 $9
1 2 3 4 5 6 7 8 9 10 11 12
fIgure 5-9 LxplanaLion o shiLin more Lhan one parameLer
Values
ParameLers are shiLed Lhree posiLions
so Lhe irsL Lhree values drop o
Causes Lhe daLa Lo be shiLed
Lhree posiLions
180 Chapter 5 Shell ScrIpt ProgrammIng Concepts
UnderstandIng Parameters 181
4. 1ype the tolloving lines ot code to create a script that shitts the parameters
tvo times
echo $1 $2 $3 $4 $5 $6 $7 $8 $9
shift 5
echo $1 $2 $3 $4 $5 $6 $7 $8 $9
shift 2
echo $1 $2 $3 $4 $5 $6 $7 $8 $9
3. Save the tile as Shift1henAgain, and then close vi.
6. 1ype chmod ugo+x ShiftThemAgain, and then press Lnter.
7. 1o execute the script, type ShiftThemAgain 1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16, and then press Lnter.
8. Perun the script and pass 16 ditterent values to it on the command line.
9. Close your vindov, and then log out.
Nov you have created a script tor passing and shitting values.You can modity it as you
see tit. Consider the potential tasks tor vhich you could use this script. Hov might you
modity it to make it best serve your needs
As you can see, it is an advantage to be able to pass parameters to a script. Hovever, the
names ot the positional parameters do not describe the data they contain, and this can
seem like a complication vhether you are using tvo parameters or several. lortunately,
you can have positional parameters take on more descriptive names. lor example, it $l
represented someone`s name and $2 represented his salary, you could vrite a shell script
fIgure 5-10 1he DonaLedSum scripL wiLh ouLpuL
5
that set the variables to the positional parameters. Peviev the shell script, named
NameSalary
Name=$l
Salary=$2
echo $Name
echo $Salary
You could execute the script as NameSalary "Jose Cruz" 50000. In the above
script, the tirst statement, the variable named Name contains the contents ot the tirst
parameter, vhich is ose Cruz. Quotes are required so the shell knovs that both the
tirst and last name represents the tirst positional parameter. It you leave the quotes ott,
the shell interprets ose as $l and Cruz as $2, or Salary.
In the second statement, the variable named Salary contains the contents ot the second
parameter. linally, the tvo echo statements display the contents ot the Name and Salary
variables, respectively.
1he benetit ot setting a descriptive name to equal the contents ot a positional parameter
is you can reterence the data by using a variable that actually describes the data. In other
vords, $Name, brings to mind someone`s name, vhereas $l does not.You can later reter
to Name and teel contident this variable contains someone`s name, and this makes
moditications to your script easier. ligure 3-11 shovs the NameSalary script as vell
as tvo executions ot that script and their output. 1he tirst command, cat
NameSalary, displays the contents ot the script.1he second command, NameSalary
"Jose Dutch" 50000, executes it correctly because quotes are included around the
name. Hovever, the third command, NameSalary Jose Dutch 50000, executes the
script incorrectly, notice there are no quotes around the name ose Dutch.
fIgure 5-11 NameSalary scripL alon wiLh Lwo execuLions and Lheir respecLive ouLpuL
182 Chapter 5 Shell ScrIpt ProgrammIng Concepts
UnderstandIng Parameters 183
SpecIal Parameters
1he shell uses special parameters to pertorm specitic tasks such as reterring to such
items as the number ot positional parameters given to a script, the name ot the script,
the PID ot the shell, or the status ot a command. Special parameters cannot be
assigned values by you. You can only reterence the contents ot special parameters
using the special parameter symbols.1he actual symbols expand into other values. Some
ot the special parameters used by the shell are described in 1able 3-3.
As vith positional parameters, in order to reterence a special parameter, you must precede
it vith the dollar sign ($,. lor example, it you vanted to display the current PID ot your
shell, you vould enter echo $$ at the command line. By combining text vith special
parameters you can create more user-triendly scripts. lor example, it you place the
command echo "The number of parameters is:" $# in a script, the command
displays the text 1he number ot parameters is tolloved by the actual number ot
parameters passed to the script.
1ake a look at the code tor the sample script named LxitStatus shovn in ligure 3-12,
vhich utilizes the special parameter $? to determine the exit status ot a previously
executed command. Notice also that ligure 3-12 includes a breakdovn ot hov each
line ot code tunctions.
Pecall that an exit status ot zero indicates success, and a nonzero exit status indicates
tailure. 1hus, the second rm payroll.dat vill tail because the tile vas previously
removed. ligure 3-13 shovs the output ot this script, shoving both the successtul and
tailed exit statuses.
Ot course, this is merely an example, you vould not place tvo rm statements in tandem
that remove the same tile. Hovever, vhat you can learn trom this is that you can use the
exit status to determine it a command tailed or not. It the script did tail, you could send
a message to the user, append the message to a tile, or both.
SpecIal Parameter DescrIptIon
@ Lxpands inLo all o Lhe posiLional parameLers sLarLin aL 1
# Lxpands Lo Lhe number o posiLional parameLers
? Lxpands Lo Lhe exiL sLaLus o Lhe command
previously execuLed as a oreround process
$ Lxpands Lo Lhe PlD o Lhe shell
! Lxpands Lo Lhe PlD o Lhe previously execuLed backround process
1able 5-3 DescripLion o some o Lhe special parameLers used by Lhe shell 5
Next you vill turther your understanding ot special parameters.
1o understand special paraneters:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation
vindov.
2. Create a script named SpecialParans in the $HOME/bin directory.
fIgure 5-13 1he LxiLSLaLus scripL and iLs ouLpuL
cd $HOME
touch payroll.dat
rm payroll.dat
echo "Exit status: "$?
rm payroll.dat
echo "Exit status: "$?
fIgure 5-12 Code and iLs explanaLion or Lhe LxiLSLaLus scripL
Chanes Lo your home direcLory
CreaLes Lhe ile
Removes Lhe ile
Displays exiL sLaLus; will succeed (sLaLus o zero)
Displays exiL sLaLus; will ail (sLaLus o nonzero) because payroll.daL
has already been removed
ALLempLs Lo remove ile aain
184 Chapter 5 Shell ScrIpt ProgrammIng Concepts
UnderstandIng Parameters 185
3. Insert the tolloving lines ot code, noting that the command named pwdx
intentionally tails and the resulting exit status retlects this
pwd
echo "Exit status of last command is:" $?
pwdx
echo "Exit status of last command is:" $?
echo "Script name is:" $0
echo "The number of parameters passed is:" $#
4. Save the script, close vi, and then change the tile permissions so you can
execute the script by name.
3. Lxecute the script. 1he script executes and displays an exit status ot zero tor the
command that runs correctly and displays a nonzero exit status tor the invalid
or incorrect command. ligure 3-14 shovs the contents ot the SpecialParams
script tolloved by its output.
6. Close your vindov, and then log out.
UsIng a Usage Clause
You can use the special parameter $# to determine it the appropriate number ot parameters
are entered by the user.1his implementation is called a usage clause. A usage clause is a
statement that displays a message indicating hov to execute the script it it is executed
incorrectly. Lsage clauses are typically used vith positional parameters that are entered on
the command line tolloving the script name. lor example, it a script requires three posi-
tional parameters, and you only enter tvo ot them, the script can detect that only tvo vere
fIgure 5-14 1he conLenLs o Lhe SpecialParams scripL and iLs ouLpuL
5
entered, and then display a usage clause indicating hov to execute the script successtully.
1he special parameter $#, used to reterence the total number ot positional parameters, is
used in an if statement. (1he details ot if statements are covered in Chapter 6., 1he tol-
loving example checks to see it three positional parameters have been entered on the
command line. 1he special parameter contains the actual number ot positional parame-
ters entered, in this case three. It a programmer enters less than three parameters, then a
usage clause message is displayed. linally, any subsequent statements execute.
if $# ~lt 3
then
echo "Usage $0 valuel value2 value3"
fi
ligure 3-13 shovs a sample script that contains the components used in this section.
fIgure 5-15 Sample scripL displayin commenLs, variable declaraLion, iniLializaLion, and
a usae clause
Variable declaraLions
Variable iniLializaLion
Nakes 1axRaLe readonly
once iL is iniLialized
Usae clause
186 Chapter 5 Shell ScrIpt ProgrammIng Concepts
CreatIng InteractIve ScrIpts 187
'RA1ING -N1RAC1IV 7CRIP1S
Although you can use positional parameters to input data into a script, there is another
approach that allovs you to prompt the user tor data called the interactive nethod.
1he interactive method uses the read command to prompt tor user input.
1he benetit ot using the read command is that you can prompt users tor input at the
time you need the input.With positional parameters, all ot the input must be knovn prior
to command execution. With the read command, you can create a descriptive variable
name to contain the data vithout having to rename it as you sav in an earlier section ot
this chapter. Iater, in the script, you can reter to the data by using the variable name.
1here are no positional parameter names to vorry about.
A common use ot the read command in scripts is vhen you vant a user to respond
vith either Yes or No to a prompt such as Do you vant to continue. 1he read
command tollovs the general tormat
read var1ao1e~name
1his is vhere var1ao1e~name is the name ot a variable, not a positional parameter.
Once you read data in the variable name, you can display the data by reterencing the
variable by name. Iook at this simple example.
read valuel
echo $valuel
In this script there are tvo statements. 1he tirst statement reads data trom the keyboard
and places it into a variable named value1.1he shell vaits tor the user input data tolloved
by Lnter. 1he second statement displays the variable`s content on the screen.
You can make the script a bit more user-triendly by indicating the type ot data you
are requesting trom the user. It you precede the read statement vith the echo ~n
statement, you can display a message, thereby letting the user knov vhat he or she needs
to enter. 1he ~n option ot the echo statement suppresses a nevline, so the cursor does
not move to the next line. Next, you vill use the read command to accept data.
1o understand the read connand:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation
vindov.
2. Create a script named ReadHobby in the $HOME/bin directory
3. 1ype the tolloving lines ot code to display a message statement, read the
value entered, and then display the value
echo -n "Enter your favorite hobby:"
read hobby
echo "You entered:" $hobby
5
4. Save the script, close vi, change the tile permissions so you can execute the
script by name, and then execute the script. Peter to ligure 3-16 and you see
the contents ot the script and execution vith the text Weight Iitting
entered into the script. Once entered, the text is displayed.
3. Modity the script to remove the ~n option ot the echo statement.
6. Lxecute the script again noticing the ditterence vhen using the ~n option
and not using it.
7. Close your vindov, and then log out.
Iike many ot the other commands that you`ve learned about, the read command has
some important options. 1hey are listed in 1able 3-4.
Option Description
~p romt Use Lo display romt as a LexL messae Lo prompL Lhe user or
inpuL; Lhis is an alLernaLive Lo usin Lhe echo~n sLaLemenL
~s Use Lo suppress echoin characLers on Lhe screen
useul or suppressin passwords
~t t1meout Use Lo Lime ouL, or expire, Lhe command once
t1meout seconds have been exceeded
~a array~name Use Lo read daLa inLo an array (arrays are discussed in ChapLer 8)
1able 5-4 Some opLions used by Lhe read command
fIgure 5-16 ReadHobby scripL and iLs ouLpuL
188 Chapter 5 Shell ScrIpt ProgrammIng Concepts
CreatIng InteractIve ScrIpts 189
Iet`s use a tev ot these options in the tolloving script
read ~t 3 ~s ~p "Enter password:" password
echo $password
In the tirst statement ot this script, the read command displays the text Lnter passvord
on the screen vhich is the text tor the prompt that tollovs the ~p option.1he ~s option
suppresses the characters displayed on the screen vhen the user enters characters in
response to the prompt. 1he data is placed in the variable named passvord. 1he ~t 3
option specities that it a key is not pressed vithin three seconds, the command times out,
or stops. Processing then continues vith the next statement.
You don'L have Lo use all o Lhe opLions on Lhe read command aL Lhe same
Lime. You can use each opLion individually.
ProtectIng a VarIable
Once you have set a variable, there may be times vhen you don`t vant it to change.
What can you do to protect the contents ot your variable against accidental change once
its value has been set You can use the readonly command to ensure that another user
cannot change the variable.
1he advantage ot using the readonly command is that you are able to protect the
contents ot a variable. 1his can prove usetul tor constant values you don`t vant to
change once set. An example might be the tax rate. You may vant the user to enter a
tax rate tor ditterent states. It the tax rate is entered as 3, tor 3, you don`t vant this to
be changed to a ditterent value later in the script. Lse ot the readonly command in
this case serves to protect the value ot the variable. Iook at the tolloving sample code
tor a script named ZipCode
read ~p "Enter Zip Code: " Zip
echo "Zip Code is: " $Zip
readonly Zip
read ~p "Attempting to change Zip Code: " Zip
echo "Zip Code is: " $Zip
ligure 3-17 displays the ZipCode script output. Notice the value is initially set to
30044. Next, the variable is set to read-only. 1hen, there is an attempt to set it to
60303, resulting in an error because the variable is read-only. 1he last statement dis-
plays the original value, 30044.
8MT
5
9NDRS1ANDING (UGGING
One important aspect ot learning any programming language is understanding hov to
debug a program. Debugging is troubleshooting errors that may occur during the
execution ot a script. You need to understand debugging techniques so you can
quickly and ettectively locate an error and correct it. 1he tolloving tvo commands
can help you debug a shell script
echo
set
UsIng IGLS
1he simplest method you can utilize tor debugging is to use the echo statement to display
the contents ot a variable at ditterent points in the script. Pecall the ZipCode script, the
echo statement is used there to display the contents ot a variable. lirst, the data is entered,
and then it is displayed on the screen. It you are only using the echo statement tor
debugging purposes, you should consider removing it once the user vorks vith the
script to keep your script clean and to the point.While displaying additional values may
help you, especially vhen you are debugging, these values may just contuse other users.
Although the echo statement can shov you the value in a variable or parameter, it cannot
very easily shov you the tlov in a script.1o accomplish this, you use the set command.
fIgure 5-17 1he ZipCode scripL ouLpuL
190 Chapter 5 Shell ScrIpt ProgrammIng Concepts
UnderstandIng DebuggIng 191
UsIng WIX
Another approach to debugging is to use the set command.1he set command is a shell
builtin command that has numerous options. 1vo ot its options used in combination
allov you to see line by line vhat is going on in the script.You vant to use this approach
it you need to understand the logical tlov ot a script. 1he ~v option prints each line as
it is read. 1he ~x option displays the command and its arguments.You can arrange the
options in any order vith the set command.
You should noL keep Lhe set opLions on or users. 1he set command ives
Lhem Loo much deLail and may resulL in unnecessary phone calls askin or help.
1he minus sign allovs you to use the options. You turn the options ott using the plus
sign. lor example, set ~xv, turns the options on vhile set +xv turns them ott.
Although this may seem contradictory, it is hov they vork.
Generally, you place the statement set ~xv at the beginning ot the script or immediately
prior to the statement you vant to begin debugging.You place the statement set +xv at
the end ot the script or someplace in the script vhere you are certain you no longer need
it. Next you vill use the set command to debug the ZipCode script.
1o understand the set statenents in order to debug:
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named ZipCode in the $HOME/bin directory. 1his is the
same code that is used to create the results shovn in ligure 3-17.
3. 1o set debugging on, enter the tolloving statement as the tirst line ot the script
set -xv
4. Nov, enter the code tor the script
read -p "Enter Zip Code: " Zip
echo "Zip Code is: " $Zip
readonly Zip
read ~p "Attempting to change Zip Code: " Zip
echo "Zip Code is: " $Zip
3. 1o set debugging ott, enter the tolloving statement as the last line ot the script
set +xv
6. Save the script, and then close vi.
7. Change the tile permissions so you can execute the script by name, and then
execute the script.1ype 30044 at the tirst prompt tor setting the value ot Zip.
1ype 44440 at the second prompt vhere you attempt to change the Zip Code.
8MT
5
1he result is you cannot change the value at the second prompt. Also, extra
text is displayed due to debugging. ligure 3-18 shovs the ZipCode script
vith debugging options. 1he tirst statement simply displays the contents ot
the ZipCode script. 1he second statement is the script`s execution. Notice as
the script runs, the tvo plus symbols, , are located to the lett ot the state-
ment as it is executing.
8. Close your vindov, and then log out.
You can also use a command named script or debuin purposes. You
run Lhe command prior Lo execuLin Lhe scripL. When Lhe scripL is inished,
press CLrl+D Lo LerminaLe Lhe script command. 1he ouLpuL is conLained in
a ile named "LypescripL." 1his is very similar Lo usin Lhe set command.
8MT
fIgure 5-18 1he conLenLs o Lhe ZipCode scripL usin Lhe set command
1urns debuin on
and o
1wo plus sins ++ indicaLe
LhaL Lhe command is bein
execuLed
192 Chapter 5 Shell ScrIpt ProgrammIng Concepts
Chapter Summary 193
'HAP1R 7UMMARY
Programs execute statements sequentially, or one atter the other. Because a shell
script is a program, it tollovs the same rule.You can break dovn the logic ot a
problem`s solution into pseudocode using statements that are not specitic to the
programming language. A pseudocode statement describes vhat is needed to
accomplish a task vithout being concerned vith the actual syntax ot the language.
In managing shell scripts, you must be avare ot tvo tactors moditying the permissions
ot a script and placement ot the script.You use the chmod command to modity a
script`s permissions. In order to execute the script by simply specitying the script`s
name on the command line, you need to give the script execute permission and place
the script in a directory that is on the search path.1he $PATH variable contains a list
ot directories that are searched vhen the shell attempts to locate a command.
1o have a complete understanding ot the basic components ot a script you need to
be tamiliar vith hov to use comments, specity the command interpreter, manage
variables, and use a usage clause.You should place comments in your script to
describe the goal ot the script. 1he comments should include your name, the date,
the name ot the script, required positional parameters, and any moditications you
make to your script. Comments tell others vhat your script is doing.You should
also specity the command interpreter to ensure that all commands are running in
the correct shell.Variable names need to describe their contents.You should declare
and initialize all variables used in your program. Also, you should use a usage clause
vhen using positional parameters in a script.
1he shell uses tvo types ot parameterspositional parameters and special parameters.
Positional parameters allov you to place values on the command line tolloving the
script`s name. 1his data can be used inside the script. 1he positional parameters
range trom 0 to 9. 1he $0 positional parameter represents the script`s name. It you
have more than nine, you must shitt the parameters using the shift command. 1he
shell uses special parameters to accomplish tasks such as displaying the exit status ot a
command or displaying the number ot parameters passed to a script.You cannot
change special parameters. 1he most usetul special parameter is ? vhich is used tor
checking exit status.
You can create scripts that allov tor user interaction by using the read command.
1his allovs you more control over the variable names because you can detine their
names at the time you ask tor input.You can use the readonly command to prevent
a variable`s contents trom changing.
You can debug your script vith the set~xv command. 1his command displays
each line and variable as it is executed. 1he set+xv command turns ott debugging.
You can also use the echo command to display the contents ot variables. Hovever,
make sure you delete or comment out the echo statement vhen you no longer need
them tor debugging purposes.
5
6VIW 5US1IONS
1. describes a set ot statements that establish the logic ot actual
program code.
a. Script
b. Machine code
c. Pseudocode
d. Binary executable
2. Which ot the tolloving uses the bash shell tor the command interpreter in a script
a. /bin/bash
b. # /bin/bash
c. !/bin/bash
d. #!/bin/bash
3. What is the name ot the directory located in your home directory that is usually
on the search path (It a script is in this directory, it can be executed vithout
entering the tull path name ot the script.,
a. $HOME/bin
b. bin
c. usrlocalbin
d. $PATH
4. What is the name ot the shell builtin variable that is used tor searching directories
vhen you enter a command or script name
a. $HOME
b. $ENV
c. $$
d. $PATH
3. What does the positional parameter $0 reterence
a. the tirst parameter tolloving the script name
b. the exit status ot the previous command
c. the name ot the script
d. the very last positional parameter
194 Chapter 5 Shell ScrIpt ProgrammIng Concepts
RevIew QuestIons 195
6. is the concept ot setting a variable to a beginning value.
a. Declaration
b. Initialization
c. Lsage clause
d. A signal
7. 1he command is used to set and unset permissions.
a. trap
b. kill
c. echo
d. chmod
8. 1he command allovs you to use more than nine positional
parameters.
a. trap
b. kill
c. shift
d. chmod
9. What special parameter is used to determine the exit status ot a previously executed
command
a. *
b. ?
c. #
d. 0
10. What command sets the permissions ot a tile named payroll.dat to be read, vrite, and
execute tor the ovner, read and execute tor the group, and no access tor others
a. chmod 750 payroll.dat
b. chmod 742 payroll.dat
c. chmod 057 payroll.dat
d. chmod 776 payroll.dat
11. You can implement to indicate to a user hov many positional
parameters to pass to a script.
a. a declaration ot an integer
b. an initialization ot a variable
c. a usage clause
d. pseudocode
5
12. You use the symbol to mark the beginning ot a comment in
a script.
a. !
b. #
c. $
d. <
13. What command sets the permissions ot a directory named HumanPesources to
be read, vrite, and execute tor the ovner, read and vrite tor the group, and read
tor others
a. chmod 764 HumanResources
b. chmod 744 HumanResources
c. chmod 742 HumanResources
d. chmod 706 HumanResources
14. You can use the command to retrieve data interactively in a
script.
a. readonly
b. read
c. echo$l
d. shift
13. What command is used to detine a variable as an integer
a. declare~i
b. define~i
c. shift
d. readonly
16. 1he command is used to prevent a variable trom changing.
a. read
b. declare
c. shift
d. readonly
17. What is the result ot the tolloving script
#!/bin/bash
# echo $l $2
echo $3
echo $?
a. 1he positional parameters, $l, $2, and $3, and the total number ot positional
parameters are displayed.
b. 1he positional parameters, $l, $2, and $3, and the exit status are displayed.
196 Chapter 5 Shell ScrIpt ProgrammIng Concepts
Hands-on Projects 197
c. 1he positional parameter $3 and the exit status are displayed.
d. 1he positional parameter $3 and the number ot positional parameters are
displayed.
18. You use the command to determine the PID ot a process.
a. ps
b. declare
c. grep
d. readonly
19. You use the command to debug a script.
a. set ~xv
b. set +xv
c. grep
d. read
20. What special parameter is used to determine the number ot positional parameters
passed to a script
a. *
b. ?
c. #
d. 0
,ANDSON 4ROJC1S
Project 5-1
In this project, you vill turn pseudocode into an actual shell script.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named ProjectS-1 in your $HOME/bin directory tor the
tolloving pseudocode
lurn oe|uin on.
Iia.e a referen.e to the |ash sheii interpreter in the s.ript.
Iia.e some appropriate .omments at the |einnin of our s.ript.
Peoire.t the oate to a neu fiie nameo tmpiist.txt.
ppeno a iistin of the .urrent users tothe same fiie.
ppeno the .ontents of the sear.h path :aria|ie to this same fiie.
Cop tmpiist.txt to our home oire.tor ano name it :HMLIroje.t1.txt.
Pemo:e the fiie nameo tmpiist.txt.
lurn oe|uin off.
3. Save the script, close the editor, make the script executable, and then execute
your script.
,ERHWSR
4VSNIGX
5
4. Close your vindov, and then log out.
Project 5-2
In this project, you vill vrite a script that calculates an average ot tive values passed as
positional parameters.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named ProjectS-2 in the $HOME/bin directory.
3. Insert a reterence to the bash shell, appropriate comments, and your name as author.
4. Accept tive positional parameters trom the command line.
3. Display all tive values on the screen.
6. Display a usage clause it the incorrect number ot values is entered.
7. Display an average ot the tive values.
8. Save the script, close the editor, make the script executable, and then execute the
script.
9. Pecord the output.
10. Close your vindov, and then log out.
Project 5-3
In this project, you vill shitt positional parameters.You vill pass 13 numbers to a script,
and then display their sum. You vill also modity one ot the scripts, named sum1, used
as an exercise in this chapter.You vill use sum1 as a guide to complete this project.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Copy sun1 to ProjectS-3 in the $HOME/bin directory.
3. Insert a reterence to the bash shell vith the appropriate comments, including your
name as the author. Indicate that this is a moditication ot the original script, the
date ot moditication, and a description ot the moditication (see Steps 4 through 8,.
4. Clear the screen vith the clear command.
3. Display the script name. (Hint Lse $0.,
6. Display today`s date.
7. Allov the script to accept 13 values.
8. Display the sum ot the 13 values.
9. Save the script, close the editor, make the script executable, and then execute
the script.
10. Close your vindov, and then log out.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
198 Chapter 5 Shell ScrIpt ProgrammIng Concepts
Hands-on Projects 199
Project 5-4
In this project, you vill pertorm calculations in interactive scripts using the read command
to accept variables trom the keyboard and display their average.You vill modity the script
created in Project 3-2 to read three numbers trom the keyboard.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named ProjectS-4 in the $HOME/bin directory.
3. Pead three values trom the keyboard.
4. Declare the variables as integers, initialize the variables to zero, and then once the
variables are read, make them read-only.
3. Set a timeout value ot tive seconds tor each variable.
6. Display the contents ot the variables.
7. Attempt to change them again.
8. Save the script, close the editor, make the script executable, and then execute
the script.
9. Close your vindov, and then log out.
Project 5-5
In this project, you vill pertorm exponentiation in interactive scripts using the read
command to accept tvo variables and then raise one to the pover ot the other. Once
the ansver is displayed, you vill unset all variables using the unset command.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named ProjectS-S in the $HOME/bin directory.
3. Declare three variables as integer, x, y, and A. Pead x and y in trom the keyboard.
Compute the ansver, A, as x raised to the y
XL
pover, and then display the ansver.
4. Lnset the variable vith the unset command.
3. Save the script, close the editor, make the script executable, and then execute
the script.
6. Close your vindov, and then log out.
Project 5-6
In this project, you vill create a script that accepts a variable. 1he variable vill be sup-
pressed, thereby emulating passvord entry.You vill use the read command to accept a
variable trom the keyboard. When the variable is read, the characters must not be dis-
played back to the user on the screen.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named ProjectS- in the $HOME/bin directory.
3. Clear the screen, and then display the message Lnter passvord on the screen.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
5
4. Pead the variable tor the passvord, but suppress characters trom displaying on the
screen as the user types them. Lse a timeout value ot your choosing to limit the
amount ot time the user has to enter the value.
3. Save the script, close the editor, make the script executable, and then execute
the script.
6. Close the vindov, and then log out.
Project 5-7
In this project, you vill pertorm computations on positional parameters as vell as
implement a usage clause by creating a script that calculates a net amount based on
sales (less costs,.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named ProjectS-7 in the $HOME/bin directory, and be sure to
include the appropriate comments.
3. Set up the script to accept tvo positional parameters trom the command line and
display a usage clause it the incorrect number ot values is entered.
4. Store the positional parameters as declared integers as tollovs
Sales=$1
Costs=$2
3. Declare a variable named Net as an integer. It vill contain the ditterence betveen
Sales and Costs.
6. Calculate the ditterence betveen Sales and Costs using the variable named Net to
display an appropriate message indicating the ditterence.
7. Save the script, close the editor, make the script executable, and then execute
the script.
8. Close your vindov, and then log out.
Project 5-8
In this project, you vill properly protect data on the command line vhen it is passed to
a script by creating a script vhere you vill pass positional parameters.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named ProjectS-8 in the $HOME/bin directory, and be sure to
include the appropriate comments.
3. Clear the screen.
4. 1o accept name, address, city, state, phone number, tax number, and e-mail
account trom the command line, use the tolloving positional parameters
$l=name, $2=address, $3=city, $4=state, $5=phone number,
$6=fax number, and $7=email account.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
200 Chapter 5 Shell ScrIpt ProgrammIng Concepts
Case Projects 201
Pemember you are required to use double quotes in order to assign the value to
the correct positional parameters.
3. Display a usage clause it the incorrect number ot values is entered.
6. Display all parameters.
7. Save the script, close the editor, make the script executable, and then execute
the script.
8. Pun the script using the tolloving data
Nane: Rachael Sing
Address: 100 Last Windan Street
City: Atlanta
State: Georgia
Phone: SSS-SSS-SSS0
Fa: SSS-SSS-SSS1
Lnail: rsingdonainnane.con
9. Perun the script vith ditterent data ot your ovn choosing.
10. Pecord the output.
11. Close your vindov, and then log out.
'AS 4ROJC1S
Case 5-1
1MI needs help vriting a script that calculates net pay. 1he script needs to support the
11 items ot data that are listed belov. (^ote you must use vhole-number amounts.,
Lmployee ID
Gross Pay
lederal 1ax Amount
Social Security Amount
401K Deduction Amount
Medical Insurance
Dental Insurance
Vision Insurance
Disability Insurance
Iegal Insurance
Stock Purchase
'EWI
4VSNIGX
5
1o complete this case you need to vrite the pseudocode logic tor this script, vrite the
script using positional parameters vhere all parameters must have an amount even it it
is 0, use integers only vhen inputting the data, use comments, reterence the shell,
include variable declaration and initialization, and add a usage clause vhere appropriate.
Display the Lmployee`s ID, the Gross Pay, all ot the deductions and the Net Pay in an
appropriate manner. (Hint the Net Pay is the Gross Pay atter all the deductions have
been accounted tor.,
Case 5-2
1he Antonio Czechos Dryvall lirm has hired you to help implement a directory
structure tor them based on ligure 3-19. Because you vere called out ot tovn to aid
another customer, you cannot go to the site. In the meantime, you decide to vrite a
script that vill create the structure tor them.1o create the directory structure, complete
the tolloving tasks
1. Write the pseudocode.
2. Write a script to create the directory structure shovn in ligure 3-19.
3. 1he directory structure should start trom the AC_Dryvall directory trom vithin
your home directory.
4. Other issues
a. It the item has an extension, treat it as a tile. Othervise, consider it a directory.
b. Note the hidden tile.
c. 1he Manager1.txt tile must only have these permissions read and vrite tor the
user ovner and the group ovners. Others should have no access.
d. 1he Lmp1.txt tile must have all permissions turned on.
$HOME/AC_Drywall
Work1.doc Work2.doc .Nanaer1.LxL Lmp1.LxL Sales Admin
LasL WesL
NlS
ProjecL1 ProjecL2 ShiL1 ShiL2 ShiL3
ProducLion NarkeLin
fIgure 5-19 AC Drywall direcLory sLrucLure
'EWI
4VSNIGX
202 Chapter 5 Shell ScrIpt ProgrammIng Concepts
203
',%48)6

()'-7-32 7869'896)7
-RXLMWGLETXIV]SY[MPP
9RHIVWXERHHIGMWMSRWXVYGXYVIXLISV]
9RHIVWXERH MJ WXEXIQIRXW
9WIPSKMGEPSTIVEXSVW
9WIXLIIPMJ GPEYWIMRERMJ WXEXIQIRX
2IWX MJ WXEXIQIRXW
9RHIVWXERHXLIGEWI WXEXIQIRX
=
ou learned Mn Chapter 3 that each statement Mn a shell scrMpt Ms executed
sequentMally1here are programmMng structures, vhMch allov you to change
the sequentMal tlov DecMsMon structures test tor a condMtMon and, based upon the
result ot that test, execute one set ot statements or another, but not both Shell
scrMpts use the if statement and the case statement tor decMsMon makMng
9ND)6S8ANDIN+ ()CISION786UC8U6) 8H)O6Y
Betore you learn about the decision statements, you need to understand hov decision
theory vorks in scripts. A dIcMsMon is a choice made trom possible alternatives based on
some condition.You make decisions on a daily basisdeciding vhat to vear, choosing
vhich movie to see, and scheduling time to study tor a test. Once you`ve made your
decisions, there is usually no turning back. lor example, it you have just enough money
tor one movie, and you purchase a ticket tor a specitic one, you cannot go back and
purchase another ticket tor a ditterent movie.You made your decision.
Here`s another example.You probably have more than one route you can take trom your
home to your school. Iet`s say you are driving to school, but you are running a little
late tor the tinal exam tor your programming class. You notice that the road ahead is
blocked due to an accident. At this point, you must make a decision. Do you vait tor
the accident to clear, or do you take an alternate route Iet`s say that the logic is that it
the road is blocked, you vill take the alternate route. Once your decision is made, you
need to tollov through on the chosen path.
A decision has one enLry poinL and one exiL poinL. ln oLher words only one
seL o insLrucLions can be ollowed based on Lhe decision.
1his type ot decision making can be implemented in shell scripts as vell. In vriting your
shell scripts, you may need to have the script make a decision about a condition betore
it takes a course ot action. Once a decision is made, the script executes only one set ot
statements. In Iinux you use the if statement as a torm ot decision making. It takes the
tolloving general torm
If .onoition then
(o a.ti:it if .onoition is true
Lnoif
1his is vhere .onoition is evaluated as either true or talse. It the .onoition evaluates as true,
then the activity immediately tolloving it is pertormed. It the .onoition evaluates as talse,
then no a.ti:it is pertormed. 1he clause Lnoif is used to terminate the if logic in this
pseudocode sample. Also, the term clausI reters to vords that are used in conjunction
vith a statement, such as then or Lnoif. 1he clause then is required in shell scripts as vell
as many other programming languages.
When reerrin Lo decision sLrucLures, Lhe Lerm "sLaLemenL," or "command,"
is used Lo reer Lo an acLual decision sLaLemenL, such as if.
8MT
20 CLaTXeV 6 DecMsMoR SXVucXuVes
URHeVsXaRHMRK DecMsMoR-SXVucXuVe 8LeoVy 205
1he if sLrucLure applies Lo all prorammin lanuaes. As you are aware,
you cannoL implemenL Lhe above loic in a shell scripL wiLhouL converLin iL
inLo Lhe speciic synLax or Lhe shell's implemenLaLion o Lhe if sLaLemenL.
Here`s hov you can turn a decision into pseudocode logic. In the previous example,
it the road is indeed blocked, you plan to take the alternate route. Othervise, you
continue on your normal path. Here is the pseudocode that demonstrates this decision
et reao for s.hooi
(ri:e to s.hooi
If roao is |io.keo then
lake aiternate route
Lnoif
lake finai exam
Statements that come betore or atter the if are unattected by the condition it tests. Here
is vhat happens. All statements are executed sequentially prior to the if statement. 1he
if statement is then executed. Once the condition is evaluated, statements that tollov if
are executed sequentially as normal. lor example, you et reao for s.hooi and (ri:e to s.hooi
in that order, betore you deal vith the if statement. Once the decision has been made
regarding an alternate route, you still lake finai exam once you arrive at school, regardless
ot the route taken. What vould happen in the previous statement it the road vere not
blocked 1he ansver is that the condition ot If roao is |io.keo then vould evaluate talse.You
vould not take the alternate route but you vould still take the tinal exam.
*lowcLaVXs aRH DecMsMoR MakMRK
In programming, one ot the tools used to help you understand the logic ot decisions is
the tlovchart. 1he flovchart uses symbols to help you understand the overall tlov ot
a program. 1he tlovchart symbols and their use are listed in 1able 6-1.
8MT
6
ligure 6-1 shovs a tlovchart tor the decision made vhile driving to school.
SLarL
GeL ready or school
Drive Lo school
l road is
blocked
1ake alLernaLe rouLe
1ake inal exam
Lnd
1rue
False
*MKuVe 6-1 FlowcharL o Lhe decMsMon made whMle drMvMnK Lo school
Name Symbol UsaKe
Oval Used Lo indicaLe where Lhe lowcharL beins and ends
Paralleloram Used Lo represenL Lhe inpuL and ouLpuL o daLa
Square Used Lo represenL a processin acLiviLy
Diamond Used Lo represenL a decision
8able 6-1 DescrMpLMon o Lhe lowcharL symbols
206 CLaTXeV 6 DecMsMoR SXVucXuVes
URHeVsXaRHMRK DecMsMoR-SXVucXuVe 8LeoVy 207
URHeVsXaRHMRK XLe IPWIDecMsMoR SXVucXuVe
What vould you do it you vanted to pertorm an activity tor the talse condition ot an
if statement Because the if statement tests tor a true condition, you need to add logic
to your if statement that handles the talse condition. 1o do this, you use the eise clause.
Here`s hov the eise vorks. 1he condition is tested. It the condition tests true, then the
code statements immediately tolloving the if statement, stopping prior to the else
clause, are executed. It the condition tests talse, then the code statements immediately
tolloving the eise clause, stopping prior to the Lnoif clause, are executed. Only one set
ot statements is executed, either the true condition statements or the talse condition
statements. Peter to the tolloving pseudocode tor logic using eise in an if statement
If .onoition then
(o a.ti:it if .onoition is true
Lise
(o a.ti:it if .onoition is faise
Lnoif
Here`s an example to help understand this concept. 1he Blue Skydiving Company sells
sky diving gear and rides. 1he management vants to determine it they earned a protit
or incurred a loss this quarter.
ligure 6-2 shovs the pseudocode that has been developed to evaluate the company`s
protitability. lirst the pseudocode determines the Sales and Costs amounts. Next, the
Net ditterence is calculated. 1hen, a decision must be made. It the ditterence betveen
Sales and Costs is greater than zero, then the company earned a protit and the protit
amount is displayed. It the ditterence betveen Sales and Costs is not greater than zero,
then the company incurred a loss and the amount ot the loss is displayed. A third pos-
sibility is that the Sales and Costs could be the same, resulting in a zero ditterence.
6
9ND)6S8ANDIN+ MJ 78A8)M)N8S
You can implement decision theory in the shell similarly to hov you do it using
pseudocode. One ot the statements the shell uses to make decisions is if. Lnderstanding
the syntax ot if vill help you to vrite it correctly in a script. It you misspell any vord
in the syntax, the script generates a syntax error and your script does not successtully
execute. 1he syntax ot the if statement is as tollovs
if 11st
then
statement1
statement2
...
statementu
f1
1he if, then, and fi clauses are required. lirst, the commands in the 11st execute.
(Peter to Chapter 1hree tor a reviev ot lists., 1hen the 11st terminates vith an exit
status. 1he exit status is vhat is tested, not the commands in the 11st. It the exit status
is zero, the command statements, statement1 through statementu, tolloving the
then clause, but prior to the fi clause, are executed. It the exit status is nonzero, then
the command statements are not executed. Processing continues vith subsequent state-
ments in the script. 1he clause fi, vhich is it spelled backvards, terminates the if
statement.
An alternate vay tor vriting the shell`s if statement is using else to execute statements
it the exit status ot 11st is nonzero. 1he else clause is optional but is needed vhen
et :aies
et Costs
^et=:aiesCosts
If ^et>0 then
(ispia "Irofit of:"^et
Lise
(ispia "Loss of:"^et
Lnoif
*MKuVe 6-2 ProMLabMlMLy pseudocode or Lhe 8lue SkydMvMnK Company
208 CLaTXeV 6 DecMsMoR SXVucXuVes
URHeVsXaRHMRK MJ SXaXemeRXs 209
you vant to process commands vhen a talse condition is reached. Lsing the else clause
in an if statement takes the tolloving torm
if 11st
then
statements
else
statements
fi
NoLice Lhe indenLion o sLaLemenLs wiLhin Lhe if sLaLemenL. AlLhouh
indenLin sLaLemenLs is noL required, iL makes Lhe code more readable in case
Lhe scripL needs Lo be modiied laLer. Generally, you indenL Lhe sLaLemenLs
ollowin then as shown in Lhe various examples in Lhe secLion.
1o help you understand vhat this means, let`s look at ligure 6-3 as an example. Sven`s
lruit Stand is asking each customer vhat his or her tavorite truit is. It the customer`s
tavorite truit is the same as Sven`s, then the customer receives tree groceries tor the day.
ligure 6-3, shovs a detailed explanation ot the script.
Remember LhaL in shell prorammin, an exiL sLaLus o zero is Lrue and an exiL
sLaLus o one is alse.
8MT
8MT 6
Next you vill create a script that tests vhether the mv command successtully moved a
tile by using the if statement to test the exit condition ot the list command.
1o crIatI a scrMpt that tIsts thI IMst status of a connand
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named MovI1Ist in the $HOME/bin directory.
echo "Svens Fruit Stand"
read ~p "Enter your favorite fruit: " fruit
if $fruit = "apple"
then
echo "The" $fruit "is my favorite fruit too!"
echo "Free groceries for you for the day!"
else
echo "Although not my favorite,"
echo " the" $fruit "is good too!"
fi
*MKuVe 6-3 LxplanaLMon o Svents FruML SLand code
Displays company name
Read Lhe variable named
ruiL rom Lhe keyboard
LhaL is enLered by Lhe
cusLomer
1he ruiL LhaL is read inLo
Lhe variable named "ruiL"
is now LesLed Lo deLermine
i iL is an "apple"
1he word "Lhen" is
required or Lhe "i"
sLaLemenL; i Lhe condiLion
LesLs Lrue, Lhe sLaLemenLs
prior Lo "Lhen" buL beore
"else" are execuLed
1hese sLaLemenLs execuLe
i Lhe condiLion LesLs Lrue
1he word "else" is
required in order Lo
execuLe sLaLemenLs i
Lhe condiLion is alse
1hese sLaLemenLs are
execuLed only i Lhe
condiLion LesLs alse
1he LexL "i" is
required and ends
Lhe "i" sLaLemenL
210 CLaTXeV 6 DecMsMoR SXVucXuVes
URHeVsXaRHMRK MJ SXaXemeRXs 211
3. Insert the tolloving lines ot code to create an if statement that checks to see
it the mv command moved the specitied tile
#!/bin/bash
if mv bike1.txt bike2.txt
then
echo "Move completed successfully ~ file moved.
Status " $?
else
echo "Move completed unsuccessfully ~ file not
moved. Status " $?
fi
4. Save the script, quit the editor, and then make the script executable.
3. Create a tile named bMkI1tt. Make sure you save the tile, and then quit
the editor.
6. Lxecute the script. 1he bike1.txt tile is moved.You knov this because ot the
message echoed to the screen. See ligure 6-4.
7. Lxecute the script again. See ligure 6-4. A message indicating the tile has not
been moved is displayed. 1his is because the tile, bike1.txt no longer exists. It
vas moved in the previous step.
8. Close your vindov, and then log out.
*MKuVe 6- 1he Nove1esL scrMpL and resulLMnK ouLpuL
Shows Lhe ile bike1.LxL
exisLs prior Lo execuLion;
displays Lhe conLenLs o
Lhe Nove1esL scripL
Nove1esL is execuLed
Lwice; Lhe irsL Lime, Lhe
ile, bike1.LxL, was moved
successully (exiL sLaLus o
0); Lhe second Lime, Lhe
ile was already moved, so
Lhe ile was noL moved
aain (exiL sLaLus o 1)
6
UsMRK CoRHMXMoRal )xTVessMoRs MR aR MJ SXaXemeRX
You can use conditional expressions as vell as commands in an if statement. Lsing
conditional expressions allovs you to compare numbers, make string comparisons, and
pertorm command substitutions.1he conditional expression takes the tolloving general torm
cond1t1ona1 exress1on
1his is vhere the cond1t1ona1 express1on tests tor values being equal, greater than,
less than, or not equal. (Peter to Chapter 3 and the man pages tor additional conditional
expressions.,
1here is a space beore and aLer each pair o square brackeLs, and . l
you do noL puL a space beore and aLer each pair, you receive an error when
execuLin a scripL LhaL uses Lhese.
Next you vill create a tev scripts that utilize the if statement and that pertorm various
tests. 1he scripts vill be explained prior to creating and running them.You can then use
these samples as guides to help you create additional scripts later.
1he tirst script tests tvo positional parameters and displays a message only it the tirst
number is larger than the second.1he goal ot this activity is to help you understand hov
to implement the if statement to pertorm comparisons ot numbers.
1o crIatI a scrMpt that usIs thI if statInInt to conparI posMtMonal paranI-
tIrs usId as nunbIrs
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named NunbIrGrIatIr in the $HOME/bin directory.
3. Insert the tolloving lines ot code to create an if statement that utilizes a
conditional expression to compare tvo positional parameters
#!/bin/bash
if $1 -gt $2 ]]
then
echo $1 " is greater than " $2
else
echo $1 " is less than " $2
fi
4. Save the script, and then quit the editor.
3. Make the script executable, and then execute the script using 4 as the tirst
parameter and 3 as the second parameter. See ligure 6-3. A message displays
indicating that the tirst parameter, 4, is greater then the second parameter, 3.
8MT
212 CLaTXeV 6 DecMsMoR SXVucXuVes
URHeVsXaRHMRK MJ SXaXemeRXs 213
6. Lxecute the script again. 1his time use as the tirst parameter and 9 as the
second parameter. See ligure 6-3. Compare the ditterences in output ot this
step vith Step 4. A message indicates the tirst parameter, 6, is less than the
second parameter, 9. 1his is ditterent trom the previous run because there are
ditterent values being compared.
7. Do not log out.
Next you vill create a script that tests a declared variable named Color that is read
into the script using the read statement. 1he script vill display a message it the value
is equal to the literal string red. 1he goal ot this exercise is to help you understand
hov to implement the if statement to pertorm string comparisons.1he practical use ot
this script is to test vhether or not a value entered is equal to a string ot letters.
1o crIatI a scrMpt that usIs thI if statInInt to dItIrnMnI Mf a valuI rIad fron
thI kI]board Ms Iqual to a lMtIral strMng
1. Create a script named ColorRId in the $HOME/bin directory.
2. Insert the tolloving lines ot code. Notice that you are using the read
statement instead ot positional parameters.
#!/bin/bash
declare Color
read -p "Enter color: " Color
*MKuVe 6-5 1he NumberGreaLer scrMpL and resulLMnK ouLpuL
SLep 5: "reaLer Lhan"
messae appears
SLep 6: "less Lhan"
messae appears
6
if $Color = "red" ]]
then
echo "The color is red"
else
echo "The color is not red - it is " $Color
fi
3. Save the script, and then quit the editor.
4. Make the script executable, and then execute it. 1ype rId vhen prompted to
enter a color. See ligure 6-6. A message indicating that the color is red
appears.
3. Lxecute the script again. 1ype bluI vhen prompted to enter color. See
ligure 6-6. 1he message 1he color is not red it is blue is displayed.
6. Do not log out.
In this third script you vill use command substitution to determine it the current directory
is equal to a specitic directory. 1he goal ot this exercise is to help you understand hov to
implement the if statement using command substitution. One practical application tor
this script might be to determine it a user`s current directory is a directory they should not
be in.
*MKuVe 6-6 1he ColorRed scrMpL and resulLMnK ouLpuL
SLep 4: messae indicaLin
Lhe color red appears
SLep 5: anoLher color
messae appears
21 CLaTXeV 6 DecMsMoR SXVucXuVes
URHeVsXaRHMRK MJ SXaXemeRXs 215
1o crIatI a scrMpt that usIs thI if statInInt to dItIrnMnI Mf thI currInt dMrIctor]
Ms a spIcMfMc onI
1. Create a script named IsDMr1np in the $HOME/bin directory.
2. Insert the tolloving lines ot code to display a message based upon your
current directory. It your current directory is tmp, you are instructed to
change to your home directory. Othervise, your current directory is
displayed. Note the command dir1=`pwd` uses command substitution.
1his is discussed in Chapter 4. Also, the variable dir1 contains the output ot
the pwd command. So, it the present vorking directory is tmp, then dir1
literally equals tmp.
#!/bin/bash
dir1=`pwd` # The variable dir1 contains the output of the
pwd command.
if $dir1 = "/tmp" ]]
then
echo "Your current directory is /tmp"
echo "Change to $HOME immediately"
else
echo "Your current directory is " $dir1
fi
3. Save the script, quit the editor, and then make the script executable.
4. It you are not in the $HOME/bin directory change to it, and then execute the
script. See ligure 6-7. A message displaying your current directory appears.
3. Change to the /tnp directory, and then execute the script. See ligure 6-7. A
message appears indicating your current directory is tmp and that you need
to change out ot the tmp directory. It you compare this step to the previous
step, you see a ditterence in the messages displayed. In the previous step,
because you are in your home directory, you are not told to change directory
locations.
6. Close the vindov, and then log out.
You should nov be able to adapt the concepts presented in these scripts to other scripts
you may vrite in the tuture.
You can place Lhe enLire if sLaLemenL on a sinle line. However, you musL
use a semicolon Lo separaLe each elemenL o Lhe sLaLemenL. 1he synLax is if
PMWXthen WXEXIQIRXWfi. One line is considered Lo be if PMWX,
Lhe nexL is then WXEXIQIRXW, and Lhe lasL one is fi. 1o execuLe Lhe
ColorGreen scripL on a sinle command line, you enLer if $Color =
"green", thenecho"Thecolorisgreen",fi.
8MT
6
CoRHMXMoRal 4VocessMRK UsMRK SMRKle SquaVe &VackeXs
Instead ot using double square brackets tor conditional processing, you can use single
square brackets, and , or the test command. Because there is no set standard in the
Iinux operating system and otten several vays to accomplish the same thing, script pro-
grammers and System Administrators vrite in a style vith vhich they are most com-
tortable. Hovever, you need to bevare ot these alternatives because the system scripts
in the etcrc.dinit.d directory use them.
ligure 6-8 demonstrates the use ot double and single square brackets and the test
command.1he script contains the same logic implemented three ditterent vays to give you
an idea hov to use and test as alternatives. 1he results are the same provided you
input the same data. Another alternative is to vrite three ditterent scripts to do the same as
this one script.You can see trom the script that you could adapt this code to a script that
inquires ot a user vhether he or she vants to continue or not.1his type ot prompting logic
is usetul in menu structures, vhich vill be covered in Chapter 9.
*MKuVe 6-7 1he lsDMr1mp scrMpL and resulLMnK ouLpuL
SLep 4: messae displays
currenL direcLory
SLep 5: messae displays
currenL direcLory and
noLice Lo chane direcLories
216 CLaTXeV 6 DecMsMoR SXVucXuVes
UsMRK LoKMcal OTeVaXoVs 217
1he sinle square brackeLs are acLually a link Lo Lhe test command. So,
usin Lhe sinle square brackeLs and Lhe test command are Lhe same. 1hey
exisL or compaLibiliLy wiLh oLher shells and versions o Lhe operaLin sysLem.
8ecause sinle square brackeLs are builL inLo Lhe shell and remain in memory,
Lheir use is more eicienL because Lhe shell does noL have Lo locaLe Lhem on
disk. However, whaL Lo use is Lhe preerence o Lhe scripL prorammer.
9SIN+ 0O+ICAL 34)6A8O6S
You can implement the ^(, P, and ^l pseudocode logical operators in the shell.
1hese logical operators allov you to test multiple commands and conditional expres-
sions, as vell as allov you to make decisions based upon multiple criteria. 1he result ot
using these operators is a more povertul and tlexible logic in your scripts.
Iet`s look at the ^( operator tirst.1he shell uses tvo ampersand symbols, tor the
^( operator. It takes the tolloving torm in the shell, given tvo conditions
if cond1t1on1 cond1t1on2
then
statements
else
statements
fi
8MT
*MKuVe 6-8 1he YesNo scrMpL and MLs resulLMnK ouLpuL
6
1his is vhere each condition, cond1t1on1 and cond1t1on2, is an exit status trom
executed commands. 1he results ot each condition must return an exit status ot zero, tor
true, in order tor the statements tolloving then to execute. It either condition results in an
exit status ot one, tor talse, then the statements tolloving else execute.
Next, let`s look at the P operator. 1he shell uses ]], tvo vertical bars, tor the P
operator. It takes the tolloving torm in the shell vith tvo conditions
if cond1t1on1 ]] cond1t1on2
then
statements
else
statements
fi
In the case ot ]], only one ot the conditions must have an exit status ot zero in order tor
the statements tolloving then to execute. 1he statements tolloving else only
execute it |oth conditions return an exit status ot one.
Iastly, consider the ^l operator. 1he shell uses !, a single exclamation point, as the
^l operator. It takes the tolloving torm in the shell
if ! cond1t1on
then
statements
else
statements
fi
Here is hov this logical operator vorks. An exit status is returned trom the command, as
a cond1t1on. 1his cond1t1on is then negated. 1hat is, an exit status ot zero becomes a
one and an exit status ot one becomes zero.1hus, the ! operator negates the cond1t1on.
It is the negated cond1t1on that gets evaluated, other than that, it vorks the same as the
previous operators. It the negated cond1t1on has an exit status ot zero, the statements
tolloving then execute. It the negated cond1t1on has an exit status ot one, the state-
ments tolloving else execute.
1he loical && operaLor is more resLricLive Lhan Lhe loical ]] operaLor
because boLh condiLions musL reLurn an exiL sLaLus o zero.
Iook at the tolloving sample business scenario that creates scripts that use these condi-
tions. 1he Have lun Hotel and Pesort Sottvare Company vrites application sottvare
tor beach and mountain lodges. 1he company management vould like to give the tech-
nical support personnel vho are hourly employees (Status = "H", and vho vork
8MT
218 CLaTXeV 6 DecMsMoR SXVucXuVes
UsMRK LoKMcal OTeVaXoVs 219
the third shitt (Shift=3, an annual bonus ot s300. Betore you can vrite this script, you
need to turn this problem into pseudocode. Here is the logic
Ponus=00
Peao :tatus
Peao :hift
If :tatus=H`^( :hift='
lhen
(ispia Your |onus is `
Lise
(ispia You are oni eiii|ie for a |onus if ou are houri uorkin shift '`
Lnoif
Next you vill create the resulting script.
1o crIatI a scrMpt that usIs thI opIrator
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named ShMftBonus in the $HOME/bin directory.
3. Insert the tolloving lines ot code to initialize the bonus variable, read data
trom the keyboard, and then display results ot the data based on an if
statement that makes use ot the operator. ligure 6-9 displays the
contents ot the ShittBonus script.
Bonus=500
read -p "Enter Status: " Status
read -p "Enter Shift: " Shift
if $Status = "H" ] $Shift = 3 ]
then
echo "Your bonus for working shift $Shift is"
'$'$Bonus"."
else
echo "You are only entitled to a bonus if you are
hourly and work shift 3."
fi
4. Save the script, quit the editor, and then make the script executable.
3. Lxecute the script, and then type H vhen prompted tor Status and type 2
vhen prompted tor Shitt. See ligure 6-10. A message indicating you do not
receive a bonus appears.
6
6. Lxecute the script again, and then type H vhen prompted tor Status and 3
vhen prompted tor Shitt. See ligure 6-10. A message indicating you do
receive a bonus appears.
7. Lxecute the script a third time, and then type S (tor Salaried, vhen
prompted tor Status and 3 vhen prompted tor Shitt. See ligure 6-10. A
message indicating you do not receive a bonus appears.
8. Do not log out.
*MKuVe 6-10 OuLpuL o Lhe ShML8onus scrMpL
SLep 5: ineliibiliLy bonus
messae appears
SLep 6: bonus messae
appears
SLep 7: ineliibiliLy bonus
messae appears
*MKuVe 6-9 ConLenLs o Lhe ShML8onus scrMpL
220 CLaTXeV 6 DecMsMoR SXVucXuVes
UsMRK LoKMcal OTeVaXoVs 221
It you use the ]] operator in the ShittBonus script instead ot the 88, the logic vould
provide tor a bonus it either the Status equaled H or the Shitt equaled 3. Only one ot
the conditions needs to be true in order tor the true condition statements to execute.
Lsing the correct logical operator is important. Othervise, you can experience logic
problems. Lven vhen the script is syntactically correct, the logic you use to set up your
script can be incorrect.
In this next example, the management at the Have lun Hotel and Pesort Sottvare
Company has decided to revard the technical support personnel in the call center based
upon the amount ot calls they take and the amount ot calls they close. Calls Handled is
the amount ot calls a support person takes. Calls Closed is the amount ot calls that are
completed to customer satistaction. Here is the partial logic
If Caiis Hanoieo > 10 P Caiis Cioseo > 0
lhen
(ispia You are entitieo to a |onus`
Lise
(ispia You are oni entitieo to a |onus if the .aiis hanoieo ex.eeos 10 or .aiis
.ioseo ex.eeos 0`
Lnoif
Next you vill create the script tor the Have lun Hotel and Pesort Sottvare Company
using the logical P operator.
1o crIatI a scrMpt that usIs thI [[ opIrator
1. Create a script named Calls in the $HOME/bin directory.
2. Insert the tolloving lines ot code to read data trom the keyboard and create
an if statement that makes use ot the ]] operator
read -p "Enter the calls handled: " CallsHandled
read -p "Enter the calls closed: " CallsClosed
if $CallsHandled -gt 150 [[ $CallsClosed -gt 50 ]]
then
echo "You are entitled to a bonus."
else
echo "You are only entitled to a bonus if the calls
handled exceeds 150 or calls closed exceeds 50."
fi
3. Save the script, quit the editor, and then make the script executable.
4. Lxecute the script, and then type 19 vhen prompted tor calls handled and
40 vhen prompted tor calls closed. See ligure 6-11. A message indicating
you are entitled to a bonus appears.
6
3. Lxecute the script again, and then type 120 vhen prompted tor calls handled
and 7 vhen prompted tor calls closed. See ligure 6-11. A message indicating
you are entitled to a bonus appears.
6. Pun the script a third time, and then type 7 vhen prompted tor calls
handled and 44 vhen prompted tor calls closed. See ligure 6-11. A message
indicating you are only entitled to a bonus vhen you exceed 130 calls
handled or 30 calls closed appears.
7. Do not log out.
In the Calls script, consider vhat the result vould be it one ot the conditions vere lett
ott or the operator vere used instead ot the ]] operator. 1he script vould be syn-
tactically correct. Hovever, it vould logically be incorrect because it vould not tollov
the desires ot the management. In the case ot the input tor Steps 4 through 6, only one
employee vould be eligible tor the bonus, not tvo.
In this tinal example tor the Have lun Hotel and Pesort Sottvare Company, the man-
agement vants a script created that indicates vhether personnel vith 23 years ot service
can retire. Here is the partial logic using the ^l logical operator.
*MKuVe 6-11 1he Calls scrMpL and resulLMnK ouLpuL
SLep 4: bonus messae
appears
SLep 6: ineliibiliLy or
bonus messae appears
SLep 5: bonus messae
appears
222 CLaTXeV 6 DecMsMoR SXVucXuVes
UsMRK LoKMcal OTeVaXoVs 223
If Years of :er:i.e is ^l iess than 2
lhen
(ispia You .an retire nou.`
Lise
(ispia You uiii neeo 2 ears to retire.`
Lnoif
Next you vill create the script using the logical ^l operator.
1o crIatI a scrMpt that usIs thI ! opIrator
1. Create a script named RItMrI in the $HOME/bin directory.
2. Insert the tolloving lines ot code to read data trom the keyboard and create
an if statement that makes use ot the ! operator
read -p "Years of Service: " Years
if ! $Years -lt 25 ]]
then
echo "You can retire now."
else
echo "You will need 25 years to retire."
fi
3. Save the script, quit the editor, and then make the script executable.
4. Lxecute the script, and then type 32 vhen prompted tor Years ot Service. See
ligure 6-12. A message indicating you can retire nov appears.
3. Lxecute the script again, and then type 21 vhen prompted tor Years ot
Service. See ligure 6-12. A message indicating you need 23 years to retire
appears.
6. Close your vindov, and then log out.
Note that it you lett ott the ! operator, the code vould indicate that that you could
retire oni it you had been there less than 23 years. Ot course, this vould be incorrect
based upon the requirements ot the scenario.
Although you created the Petire script using the ! operator, you could have vritten it
vithout using this operator.You could modity the script as tollovs
read ~p "Years of Service: " Years
if $Years ~ge 25
then
echo "You can retire now."
else
echo "You will need 25 years to retire."
fi
6
Notice the main ditterence betveen the tvo versions is that they are opposite in terms
ot logic.
Nov that you`ve looked at some sample scripts using the if statement and logical oper-
ators, reviev 1able 6-2 tor a summary ot the conditions used in this section.You read this
table by looking at the evaluation ot the conditions in the Condition 1 and Condition 2
columns. Next, look to the right under the heading tor the operation you are using. lor
example, it Condition 1 is true and Condition 2 is talse, then the ^( operator result
vould be talse, and the P operator result vould be true. In the last column, only one
condition is tested, vhich is Condition 1. So, in this case it Condition 1 is true, talse is the
result ot the ^l condition operator.
CoRHMXMoR 1 CoRHMXMoR 2 CoRHMXMoR 1 CoRHMXMoR 1 NO8
AND CoRHMXMoR 2 O6 CoRHMXMoR 2 CoRHMXMoR 1
6esulX (ScVMTX uses &&) 6esulX (ScVMTX uses | |) (ScVMTX uses !)
1rue 1rue 1rue 1rue False
1rue False False 1rue False
False 1rue False 1rue 1rue
False False False False 1rue
8able 6-2 LoKMcal operaLors
*MKuVe 6-12 1he ReLMre scrMpL and resulLMnK ouLpuL
SLep 4: reLiremenL messae
appears
SLep 5: dierenL reLiremenL
messae appears
22 CLaTXeV 6 DecMsMoR SXVucXuVes
UsMRK XLe IPMJ Clause MR aR MJ SXaXemeRX 225
You can have mulLiple condiLions wiLh Lhese loical operaLors. For example,
if true && true && true, then echo "True", else echo
"False", fi displays "1rue" on Lhe screen. Also, if true && false &&
true, then echo "True", else echo "False", fi displays "False"
on Lhe screen. However usin Lhe ]] operaLor, if true ] ] false ] ]
true, then echo "True", else echo "False", fi displays "1rue"
on Lhe screen. 8uL, if false ] ] false ] ] false, then echo
"True", else echo "False", fi displays "False" on Lhe screen.
9SIN+ 8H) IPMJ 'LAUS) IN AN MJ 78A8)M)N8
1he if statement allovs you to use the optional elif clause to turther test a talse con-
dition ot an if statement. ligure 6-13 shovs the placement ot the elif clause vithin
the if statement.
1he phrase elif sLands or "else i." lL is parL o Lhe MJ sLaLemenL and
cannoL be used by iLsel. ln oLher words, you could noL have jusL Lhe elif
clause ollowed by a condiLion.
if PMWX
then
jjjWXEXIQIRXW
elif PMWX
then
jjjWXEXIQIRXW
else
jjjWXEXIQIRXW
fi
*MKuVe 6-13 PosMLMon o Lhe elif clause Mn an if sLaLemenL
if sLaLemenL wiLh
embedded elif;
elifcode will only execuLe
i Lhe exiL code is 1
SecLion o code or Lhe
elif clause o Lhe if
sLaLemenL
fi clause or Lhe enLire if
sLaLemenL
8MT
8MT
6
Lsing this torm ot the if statement, then if11st must return an exit status ot one in
order tor the elif clause to process. Once control passes to the elif clause, processing
occurs as it this vere an if statement. 1he commands that are executed tor the elif
clause begin vith the then clause and end vith the last statement prior to fi. Note that
there is only one fi clause tor the entire if statement.
It the condition tor the elif11st clause returns an exit status ot zero, then the then
statements vithin the elif statements are executed. It the condition tor the elif11st
clause returns an exit status ot one, then the else statements are executed.
l ifPMWX reLurns an exiL sLaLus o zero, Lhe sLaLemenLs immediaLely
ollowin Lhe irsL then clause are execuLed up Lo Lhe elif clause. 1hen,
processin skips Lhe elif clause alLoeLher and resumes aLer Lhe fi clause.
1o help you understand this, take a look at another business scenario. Pose`s Bubblegum and
Popcorn lactory is interested in knoving vhether they have made a protit, experienced a
loss, or broken even vith respect to their cash tlov.1hey vant a script that reads in sales and
costs and calculates their ditterence. It the ditterence is zero, they have a breakeven. It the dit-
terence is greater than zero, they have a protit, othervise, they have a loss.
Next you vill vrite the shell script to determine protitability tor Pose`s Bubblegum and
Popcorn lactory, using the elif clause.
1o crIatI a scrMpt that usIs thI elif clausI Mn thI if statInInt
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named ProfMtLossBrIakIvIn in the $HOME/bin directory.
3. Insert the tolloving lines ot code. 1he code is structured this vay because
you have three possible scenariosprotit, a loss, or a breakeven. In this
exercise, the breakeven possibility is tested tirst. 1his is simply programmer
preterence.You could test any ot the three conditions tirst. Hovever, you
vould have to change the existing code.
#!/bin/bash
read -p "Enter Sales Amount: " Sales
read -p "Enter Costs: " Costs
{{Net=$Sales - $Costs}}
if $Net -eg "0" ]]
then
echo "Profit and Costs are egual ~ breakeven."
elif $Net -gt "0" ]]
then
echo "Profit of: " $Net
else
echo "Loss of: " $Net
fi
226 CLaTXeV 6 DecMsMoR SXVucXuVes
UsMRK XLe IPMJ Clause MR aR MJ SXaXemeRX 227
4. Save the script, and then quit the editor.
3. Make the script executable, and then execute the script inputting 000 vhen
prompted tor Sales Amount and 00 vhen prompted tor Costs. See ligure 6-14.
Because Sales is less than Costs, a loss ot -1300 is retlected in a message.
6. Lxecute the script again. 1his time input 00 vhen prompted tor Sales
Amount and 00 vhen prompted tor Costs. See ligure 6-14. Here is the
breakeven. Both Sales and Costs are the same resulting in neither a protit nor
a loss. 1hus, a message indicating a breakeven has occurred is displayed.
7. Lxecute the script one tinal time and input 00 vhen prompted tor Sales
Amount and 000 vhen prompted tor Costs. See ligure 6-14. In this execu-
tion, a protit ot 1300 is displayed because Sales exceeds Costs by that amount.
8. Close your vindov, and then log out.
1here are a variety ot vays to vrite a script that yields identical results. Iet`s look at an
alternative to this script, named ProtitIossBreakeven2. In this alternate version, there are
tvo elif clauses usedone nested vithin the other. 1he vay this vorks is that it the
net amount is not equal to zero, tor a breakeven, then the tirst elif is tested. It the net
amount is zero, the tact that a breakeven exists is displayed and the script terminates.
With the tirst elif clause, it the net amount is greater then zero, you have a protit. 1he
amount ot protit is displayed and the script terminates. Only it the net amount is less
than zero vill the second elif be tested. In this case, the amount ot the loss is displayed.
Because the second elif is nested, testing ot the second elif is conditional, it is only
tested it the tirst elif results in talse. Iook back to ligure 6-14 and you see only one
*MKuVe 6-1 1he ProMLLoss8reakeven scrMpL and MLs resulLMnK ouLpuL
SLep 5: loss messae is
displayed
SLep 7: messae indicaLin
proiL is displayed
SLep 6: messae indicaLin
breakeven is displayed
6
elif clause. Iook at ligure 6-13 and you see tvo elif clauses. It you compare the
tigures, you see the end result is the same.
2)S8IN+ MJ 78A8)M)N8S
As you are creating more and more complex scripts, you may tind that one condition
depends on the result ot another. Similar to nested elif statements, the shell allovs you
to nest your if statements, meaning that you can create a complete if...then...fi
statement vithin another if...then...fi statement. With nesting, you can have
vhole sections ot code embedded vithin other vhole sections ot code.
Consider the tolloving example. An organization named Iucy`s Books and 1apes, Inc. has
specitic retirement requirements. An employee must have 23 years ot service regardless ot
age, or an employee must have 10 years ot service and be at least 60 years ot age in order
to retire. ligure 6-16 demonstrates this example. 1he tirst if is a data validation test.
Although not a stated requirement, it makes sense tor the employee`s age to be less than
the number ot years. It this vere not in the script, then the script vould technically allov
someone to be 13 years old vith 30 years ot service. Because it is not possible tor the age
to be less than the years ot service, it needs to be considered as part ot the script. Many
times, you must go beyond the stated requirements ot a program to prevent inaccurate data
trom getting into the scripts.
*MKuVe 6-15 1he ProMLLoss8reakeven2 scrMpL wMLh Lwo elif clauses
ScripL uses Lwo elif
clauses, buL Lhe end
resulLs is Lhe same as
Lhe ProiLLoss8reakeven
scripL seen previously
228 CLaTXeV 6 DecMsMoR SXVucXuVes
NesXMRK MJ SXaXemeRXs 229
DaLa inLeriLy is discussed in reaLer deLail in ChapLer 9.
8MT
read~p"EnterAge:"Age
read~p"EnterYearsofService:"Years
if$Age~ge$Years
then
if$Age~ge60&&$Years~ge10
then
echo"Youmayretire!"
else
if$Years~ge25
then
echo"Youmayretire!"
else
echo"Inordertoretire,youmustbe
atleastage60with10Yearsof
Serviceor"
echo"have25yearsofservice."
fi
fi
else
echo"YourageislessthanyourYearsof
Service!Thisisinvalid!"
fi
*MKuVe 6-16 Lucyts 8ooks and 1apes, lnc reLMremenL requMremenLs scrMpL
Read Lhe daLa
l Lhe employee is aL
leasL 60 and has aL
leasL 10 years wiLh
Lhe oranizaLion, Lhe
employee can reLire
1he Ae musL be reaLer
Lhan Lhe number o
Years o Service
l Lhe employee is noL
aL leasL 60 wiLh 10
years, check Lo see i
Lhe employee has aL
leasL 25 years wiLh
Lhe oranizaLion
1his else is done
i none o Lhe
condiLions are meL;
Lhis fi ends
Lhe 25 Years o
Service LesL
1his fi ends Lhe
Ae and Years LesL
1his fi ends Lhe Ae
reaLer Lhan Years LesL
6
Next you vill create the script shovn in ligure 6-16.
1o crIatI a scrMpt that usIs thI nIstId if statInInts
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named RItMrInIntStatus in the $HOME/bin directory.
3. Insert the lines ot code shovn in ligure 6-16 to create a script that uses
nested if statements.
4. Save the script, and then quit the editor.
3. Make the script executable, execute the script, and then input 0 vhen
prompted tor Age and 10 vhen prompted tor Years ot Service. See ligure 6-17.
A message indicating you have not met the requirements appears.
6. Lxecute the script again. 1his time input 2 vhen prompted tor Age and 2
vhen prompted tor Years ot Service. See ligure 6-17. A message indicting
you have met the requirements appears.
7. Lxecute the script one last time. Input 1 vhen prompted tor Age and 20
vhen prompted tor Years ot Service. See ligure 6-17. A message indicating
that your input is invalid appears.
8. Close your vindov, and then log out.
Iet`s take a look at a more complex example ot a script using nested if statements. In
this example, Hugh Nguyen Airvays needs a script to help vith the passenger-booking
system.1his script vill serve as a prototype tor the company`s main booking system that
*MKuVe 6-17 LxecuLMon o Lhe ReLMremenLSLaLus scrMpL
SLep 5: reLiremenL messae
appears
SLep 6: a dierenL
reLiremenL messae
appears
SLep 6: invalid messae
appears
230 CLaTXeV 6 DecMsMoR SXVucXuVes
NesXMRK MJ SXaXemeRXs 231
vill be vritten in another programming language. 1he company needs a program that
determines the price ot a tare tor a booking. ligure 6-18 demonstrates the logic that the
script needs to tollov to meet the demands ot the passenger-booking system.
ligure 6-19 shovs the actual script that applies the logic shovn in the tlovchart
in ligure 6-18. Notice that the Airlare script shovn in ligure 6-19 accepts three
variablesDestCity, Class, and WeekDay, and determines the price based upon these
inputs. 1he logic established in ligure 6-18 maintains that it the passenger travels to
Ios Angeles (city code ot IAX, and is in Coach class (Class C,, he or she vill pay
an airtare ot s30 tor travel on a Saturday and s73 tor travel any other day. It the
passenger travels to Ios Angeles in any other class, he or she pays an airtare ot s80.
Airtare to any other city is s100.
SLarL
GeL DesLCiLy,
Class, Weekday
DesLCiLy=
"LAX"
Air Fare=$100
Lnd
1rue
False
Class="C"
WeekDay=
"SaL"
1rue 1rue
Air Fare=$80 Air Fare=$75
False False
Air Fare=$50
*MKuVe 6-18 FlowcharL o Lhe loKMc or calculaLMnK aMrare prMces
6
9ND)6S8ANDIN+ 8H) GEWI 78A8)M)N8
1he case statement is another implementation ot the decision structure.You should use
the case statement vhen you have a decision that is based upon multiple inputs such
as the teedback received trom a user based on several menu options.
AlLhouh Lhere are no seL rules, you should consider usin Lhe case sLaLe-
menL when you have Lhree or more decisions. Aain, iL is up Lo Lhe pro-
rammer Lo decide which approach Lo use.
Generally, using the case statement instead ot an if statement is more readable tor a
programmer vhen there are several inputs. Iogically speaking, the case statement tunc-
tions similarly as one large if statement.
4seuHoloKMc of XLe GEWI SXaXemeRX
Iet`s tirst look at the general logic ot the case statement
Case :aria|iename
Case1. Ierform a.ti:it if .ontents of Case1 are euai to the .ontents of :aria|iename
Case2. Ierform a.ti:it if .ontents of Case2 are euai to the .ontents of :aria|iename
Case'. Ierform a.ti:it if .ontents of Case' are euai to the .ontents of :aria|iename
8MT
*MKuVe 6-19 AMrare calculaLMon scrMpL or HuKh NKuyen AMrways
232 CLaTXeV 6 DecMsMoR SXVucXuVes
URHeVsXaRHMRK XLe GEWI SXaXemeRX 233
.
.
Case Lise. Ierform a.ti:it if none of the pre:ious Cases are euai to the .ontents of the
:aria|iename
LnoCase
Here`s hov the case statement vorks. 1he :aria|iename is tested to see it the contents
match one ot the cases, specitied as Case1, Case2, or Case', then the activity to the right
ot the match is pertormed. Once the match occurs, none ot the other cases is tested.
Processing continues to statements that come atter the case statement.You can use a case
else clause in the event there are no matches.1his clause is usetul it a user has not entered
a value trom a list ot choices that have been given.
SyRXax foV XLe GEWI SXaXemeRX
Iet`s look at the shell`s implementation ot the case statement
case word in
attern1| statements
statements
,,
attern2| statements
statements
,,
atternu| statements
statements
,,
esac
1he case statement, and the in and esac clauses are required.1he phrase caseword
in is required. 1his code phrase is analogous to the verbal phrase What case is the
pattern to match. 1he word is a variable that matches one ot the patterns. lor a
pattern, you can use characters and numbers. You can also use the pattern-matching
symbols, *, tor matching all characters, ?, tor matching a single character, or ..., tor
matching a range ot characters.
NosL scripLs use * as a orm o Lhe case else pseudocode. lL maLches anyLhin,
and iL is enerally placed aL Lhe end o a case sLaLemenL or caLchin cases LhaL
do noL maLch any previous paLLern.
1he right parenthesis symbol, | is required tor each patternu and separates each indi-
vidual case trom the statements that are to be pertormed it a match occurs tor that case.
1he ,, symbols are required and are used to terminate each case. 1he esac clause ter-
minates the entire case statement. Similar to if and fi, esac is case spelled backvards.
8MT
6
Next you vill create a simple shell script using the case statement.
1o crIatI a sMnplI scrMpt that usIs thI case statInInt
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Copy the script named $HOME/bin/ColorRed used in an earlier exercise to
a nev script named $HOME/bin/ColorRed1.
3. Modity the script so it contains the tolloving lines ot code
read -p "Enter color: " Color
case $Color in
red} echo "The color is red"
,,
*} echo "The color is not red ~ it is " $Color
esac
4. Save the script, and then quit the editor.
3. Lxecute the script. Input rId vhen prompted tor color.
6. Lxecute the script again. 1his time input bluI vhen prompted tor a color.
7. Close your vindov, and then log out.
4aXXeVR maXcLMRK aRH XLe GEWI SXaXemeRX
Suppose you vant to vrite a script that asks users to respond to a yes or no question in
order tor a specitic activity to occur. 1hey might input a Y, y, or Yes tor a positive
response.You can set up your code to allov several patterns to be matched tor one case.
1o do this, you need to use the vertical bar, ], to separate the patterns that are possible. So,
in the ColorPed1 script, you could modity the tirst pattern statement, red|echo"The
colorisred" vith red]Red]RED|echo"Thecolorisred" to accept either
red, Ped, or PLD as valid input. Any one ot these three causes 1he color is red
to display on the screen.You can think ot the ] operator as a logical P in this case.
Next you vill learn hov to use the ] operator to match one ot several possible values
in a variable. You vill use the tr command to translate the ansver into uppercase and
test the translated result. Another alternative to attempting to guess the patterns a user
may input using the ] operator, is to combine the ] operator vith the tr command to
translate the user`s input into all uppercase letters, and thus limit the number ot possible
inputs your script needs to anticipate. lor example, vhen translating characters, you
von`t have to vorry about testing multiple combinations ot Yes, yes, Y, or y tor
a positive response on the part ot the user. Command substitution is used to hold the
translated result, and that is vhat is tested in the case statement.
23 CLaTXeV 6 DecMsMoR SXVucXuVes
URHeVsXaRHMRK XLe GEWI SXaXemeRX 235
1o crIatI a scrMpt that usIs thI [ opIrator for pattIrn natchMng Mn a case
statInInt
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named YIsNoCasI in the $HOME/bin directory.
3. Insert the tolloving lines ot code to accept input trom a user, translate the
user`s input into all uppercase, and create a case statement to display the
desired tiles
read -p "Do you want to see all files? {Y or N}" YesNo
YN=`echo $YesNo [ tr :lower:] :upper:]`# Turn the
response into uppercase.
case $YN in
Y[YES}
echo "Displaying all files..."
ls -a
,,
N[NO}
echo "Displaying all files except hidden..."
ls
,,
*} echo "Invalid response!" ,,
esac
4. Save the script, and then quit the editor.
3. Make the script executable, and then execute the script. Input Y vhen
prompted. Because Y is entered, the ls ~a command is executed and
displays all tiles, including hidden tiles.
6. Lxecute the script again. Input ] vhen prompted. Because y is entered, it is
translated to an uppercase Y. Again, the ls~a command is executed and
displays all tiles, including hidden tiles.
7. Lxecute the script again. Input N vhen prompted. Because N is entered,
the ls command is executed and displays all tiles, except hidden tiles.
8. Lxecute the script another time. Input No vhen prompted. Because an n is
entered, it is translated to an uppercase N.1he ls command again executes
and displays all tiles, excluding hidden tiles.
9. Lxecute the script one last time. Input Ok vhen prompted. A message
indicating an invalid response vas entered is displayed.
10. Close your vindov, and then log out.
NoLe in Lhe nexL Lo Lhe lasL sLaLemenL LhaL Lhe ,, symbols or endin a case
are on Lhe same line as Lhe sLaLemenL. 1his is accepLable and saves some
space in your scripL. 8MT
6
CommaRH SubsXMXuXMoR aRH 4aXXeVR MaXcLMRK
You can also use the case statement to pertorm pattern matching on a command`s
output.You learned about command substitution in Chapter 4.When combining command
substitution vith pattern matching, you use the `...` or ${...| characters to substitute
the command`s output in place ot the command. 1hen, you use the case statement to
test the result. lor example, say the pwd command displays tmp as your current direc-
tory.1hen the command case`pwd`in literally translates to case tmp in. You must
then create the cases tor the patterns you vant to match.
Next you vill use the case statement, along vith command substitution, to determine
it the current directory is . It it is (,, then the current directory is changed to the user`s
home directory using the cd$HOME command.
1o crIatI a scrMpt that MncorporatIs connand substMtutMon Mn a case statInInt
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named DMrRootCasI in the $HOME/bin directory.
3. Insert the tolloving lines ot code to create a case statement that changes the
directory to the user`s home directory vhen the current directory is (,
case `pwd` in
/} echo "Changing to $HOME"
cd $HOME # Note: cd or cd - would also work.
,,
esac
4. Save the script, quit the editor, and then make the script executable.
3. Change to root.
6. Lxecute the script. A message is displayed indicating the current directory is
being changed to your home directory.
7. Close your vindov, and then log out.
MaXcLMRK IRHMvMHual 4osMXMoRs
You can create a script that uses pattern-matching techniques to match individual character
positions. ligure 6-20 shovs a script vritten tor Samuel`s Movie 1heater that helps deter-
mine the price ot an admission ticket based upon the age ot the movie goer.1he ovners ot
the theater vant the price ot admission to be as tollovs it the patron is 12 years ot age and
younger, the price is s3.00. It the patron is betveen 13 and 39, the price is s6.00. It the
patron is a senior citizen, above age 60, the price is s4.00.1he tirst pattern-matching code,
1~9]10~2, accounts tor the ages 1 through 9 or 10, 11, or 12. 1he next pattern
matching code, 13~9]2~50~9, matches the ages 13 through 19, or 20 through 39.
1he next pattern matching code, 6~90~9, matches the ages 60 through 99.
236 CLaTXeV 6 DecMsMoR SXVucXuVes
URHeVsXaRHMRK XLe GEWI SXaXemeRX 237
1he case statement is an ideal tool to use vhen you vant to create a menu system
vhere a user can enter one ot several choices.
ln ChapLer 7, you will learn how Lo build a loop around Lhe case sLaLemenL
so Lhe menu processes a selecLion and Lhen rereshes Lhe screen choices or
urLher selecLion. 1his is known as a Lrue menu sysLem.
Next you vill combine some ot the concepts you`ve learned so tar into a partial menu
script. 1his script is partial in that each selection is processed and then the script termi-
nates. 1his helps you get tamiliar vith the tundamentals tor building a menu system.
1o usI thI case statInInt to buMld a partMal nInu s]stIn
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation
vindov.
2. Create a script named ChoMcIs in the $HOME/bin directory.
3. Insert the tolloving lines ot code.1hese statements create the menu selection
numbers tor the script. A user vill be able to select a number to run a command.
echo "1. The ps command"
echo "2. The who command"
echo "3. The ls command"
8MT
ChildPrice=3
AdultPrice=6
SeniorPrice=4
read~p"Enteryourage:"age
case$agein
1~9]10~2|echo"PriceisChild'spriceof"$ChildPrice,,
13~9]2~50~9|echo"PriceisAdultpriceof"$AdultPrice,,
6~90~9|echo"PriceisSeniorpriceof"$SeniorPrice,,
*|echo"Enteravalidselection",,
esac
*MKuVe 6-20 Samuel's NovMe 1heaLer admMssMon prMcMnK scrMpL usMnK case sLaLemenLs
Lo creaLe menus
6
echo "4. View a file using the cat command"
read -p "Enter Selection: " Answer
4. Nov, insert these lines ot code. 1his creates the tirst tvo possible statements
to be executed. lor example, it the user selects 1, then the ps command
executes. It the user selects 2, then the who command executes.
case $Answer in
1} ps ,,
2} who ,,
3. Nov, insert these lines ot code.1his creates the third possible set ot statements
to be executed. lor example, it the user selects 3, then the user is prompted
to enter Y tor a long listing. It the user enters a Y, a long listing is executed.
It N is entered, then a regular listing is executed.
3} read -p "Do you want a long listing? {Y or N} " YesNo
YN=`echo $YesNo [ tr :lower:] :upper:]`
case $YN in
Y} ls -l ,,
*} ls ,,
esac ,,
6. Nov, insert these lines ot code.1his creates the tourth possible set ot statements
to be executed. lor example, it the user selects 4, then the user is prompted
tor a tilename to enter. It the tile exists, then it is displayed. It it does not exist,
a message appears indicating that the tile does not exist.
4} read -p "Enter file name to view: " FileName
if -a $FileName ]
then
cat $FileName [ more # Or more $FileName
else
echo "File does not exist!"
fi ,,
*} echo "Enter a valid selection" ,,
esac
7. Save the script, quit the editor, and then make the script executable.
8. Lxecute the script tor choice 1. A process listing is displayed because the ps
command executes.
9. Lxecute the script tor choice 3. Input Y vhen prompted to ansver the
question about the long listing. A long listing appears.
10. Lxecute the script tor choice 2. A listing ot users currently logged on is
displayed because the who command executes.
11. Lxecute the script tor choice 4 to viev an existing tile. 1ype ColorRId to
display the contents ot this tile. 1he ColorPed tile is displayed.
12. Close your vindov, and then, log out.
238 CLaTXeV 6 DecMsMoR SXVucXuVes
6evMew QuesXMoRs 239
'HA48)6 7UMMA6Y
A decision is a choice ot possible alternatives. Once a choice has been made, the
path ot the program is set.You can use decision structures to change the tlov ot a
program, thereby creating povertul programming constructs. llovcharts utilize
symbols and arrovs to represent program tlov. 1he tlovcharting symbol tor a
decision is the diamond.
One ot the shell`s decision statements is the if statement. It allovs you to test a
condition, and then pertorm statements based upon the condition.
1he shell uses the operator tor a logical ^(, a ]] operator tor a logical P,
and a ! operator tor a logical ^l.
1he optional elif clause allovs you to test another condition in the event the if
condition tests talse. When using the elif clause, there is only one if tor each
if...elif pair.
You can nest if statements by placing vhole if statements vithin other if state-
ments.You should consider nesting if statements vhen you have a condition that
depends upon the result ot a previous condition.
1he shell allovs you to use the case statement as a substitute tor the if statement.
1he best use ot the case statement is vhen one variable has several potential values.
6)VI)W 5U)S8IONS
1. 1he is the tlovcharting symbol used tor a decision.
a. diamond
b. oval
c. parallelogram
d. square
2. Which ot the tolloving uses symbols to assist you in understanding the tlov
ot a program
a. Pseudocode
b. llovchart
c. 1he case statement
d. 1he if statement
3. Given the tolloving script, vhich ot the subsequent ansvers is true
#!/bin/bash
{{x=l||, {{y=2||
if $x ~gt $y
then
echo $x $y
6
else
echo $y $x
fi
a. 1he use ot semicolons is incorrect.
b. 1he output is 21.
c. 1he output is 12.
d. 1he use ot square brackets is incorrect.
4. Given the tolloving script, vhich ot the subsequent ansvers is true
#!/bin/bash
{{x=2||, {{y={3*$x|/2||
if $x ~le $y
then
echo $x $y
else
echo $y $x
fi
a. 1he use ot semicolons is incorrect.
b. 1he output is 32.
c. 1he output is 23.
d. 1he terminating vord is misspelled.
3. A is used as a delimiter vhen an if statement is on a
single line.
a. colon
b. comma
c. semicolon
d. question mark
6. When using an if statement, you use the symbol to test that
a variable is either cat, Cat, or CA1.
a.
b. !
c. ~
d. ]]
7. You use the symbol to negate a condition in a shell script.
a.
b. !
c. ~
d. ]]
20 CLaTXeV 6 DecMsMoR SXVucXuVes
6evMew QuesXMoRs 21
8. You use the symbol as a logical AND condition in a
shell script.
a.
b. !
c. ~
d. ]]
9. Which clause vould you use it you vanted to turther test a talse condition in an
if statement
a. case
b. !=
c. else
d. elif
10. is the terminating clause tor the if statement.
a. end~if
b. fi
c. elif
d. esac
11. is the terminating clause tor the case statement.
a. end~if
b. fi
c. elif
d. esac
12. Placing a complete if statement vithin another complete if statement is called
.
a. tlovcharting
b. nesting
c. conditional processing
d. using a usage clause
13. Given the tolloving script, vhich ot the tolloving is true
#!/bin/bash
{{x=5||, {{y=l0||
if $x ~eq 5 ]] $y ~gt l2
then
echo "Hello"
else
echo "Bye"
fi
6
a. 1he output displays Hello.
b. 1he output displays Bye.
c. 1here is a square bracket missing.
d. 1he {{x=5|| statement contains incorrect syntax.
14. Given the tolloving script, vhich ot the tolloving is true
#!/bin/bash
{{x=5||, {{y=l0||
if $x ~eq 5 ]] $y ~gt l2
then
echo "Hello"
else
echo "Bye"
fi
a. 1he output displays Hello.
b. 1he output displays Bye.
c. 1here is a square bracket missing.
d. 1he {{x=10|| statement contains incorrect syntax.
13. Given the tolloving script, vhich ot the tolloving is true
#!/bin/bash
{{x=5||, {{y=l0||
if $x ~eq 5 $y ~gt l2
then
echo "Hello"
else
echo "Bye"
fi
a. 1he output displays Hello.
b. 1he output displays Bye.
c. 1here is a square bracket missing.
d. 1he {{x=5|| statement contains incorrect syntax.
16. Given the tolloving script, vhich ot the tolloving is true
#!/bin/bash
{{x=5||, {{y=l0||
if $x ~lt 5 ]] $y ~gt 84
then
echo "Hello"
else
echo "Bye"
if
22 CLaTXeV 6 DecMsMoR SXVucXuVes
6evMew QuesXMoRs 23
a. 1he output displays Hello.
b. 1he output displays Bye.
c. 1here is a square bracket missing.
d. 1here is no terminating clause.
17. Given three ^( conditions, vhat is the end result it one ot the conditions
is talse
a. 1he end result is true.
b. 1he end result is talse.
c. You cannot have three ^( conditions.
d. Statements tolloving the then in an if execute.
18. Given the tolloving script, vhich ot the tolloving is true
#!/bin/bash
{{x=5||, {{y=l0||
case $x in
l~5| echo $x
,,
echo $y
,,
esac
a. 1he output displays 3.
b. 1he output displays 10.
c. 1here is a square bracket missing.
d. 1here is no terminating clause.
19. Given the tolloving script, vhich ot the tolloving is true
#!/bin/bash
{{x=5||, {{y=l0||
if $x ~eq 4
then
if $y ~ge l0
then echo $x $y
else echo $y $x
else echo "Hi"
fi
a. 1he output displays 3 10.
b. 1he output displays 10 3.
c. 1he output displays Hi.
d. 1here is no terminating clause.
6
20. Given the tolloving script, vhich ot the tolloving is true
#!/bin/bash
{{x=4||, {{y=l0||
if $x ~eq 4
then
if $y ~ge l0
then echo $x $y
else echo $y $x
else echo "Hi"
fi
a. 1he output displays 4 10.
b. 1he output displays 10 4.
c. 1he output displays Hovdy.
d. 1here is no terminating clause.
,ANDSON 46OJ)C8S
4VoNecX 6-1
In this project, you vill create a shell script that tests vhether a tile has been removed
vith the rm command. You vill test tor the exit status ot a command`s execution and
use a decision structure to determine it the command successtully executed or not. It
the exit status ot the rm command equals zero, then the tile has been removed. It the
exit status ot the rm command equals one, then the tile has either been removed or never
existed. Pemember to turn on debugging vith set~xv it you need to troubleshoot
the script. 1urn it ott vith set+xv vhen through debugging the script.
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a shell script named ProNIct-1 in your $HOME/bin directory.
3. Insert the tolloving lines ot code
touch FileIsHere.txt
rm FileIsHere.txt
FileHereStatus=$?
if $FileHereStatus -eg 0 ]]
then
echo "File successfully removed"
else
echo "File not present"
fi
rm FileNotHere.txt
FileNotHereStatus=$?
if $FileNotHereStatus -eg 0 ]]
,ERHWSR
4VSNIGX
2 CLaTXeV 6 DecMsMoR SXVucXuVes
HaRHs-oR 4VoNecXs 25
then
echo "File successfully removed"
else
echo "File not present"
fi
4. Save the script, and then quit the editor.
3. Make the script executable, and then execute the script.
6. Pecord the results.
7. Close your vindov, and then log out.
4VoNecX 6-2
In this project, you vill create a shell script that uses the case statement to implement
a usage clause (reter to Chapter 3 tor more on usage clauses,. 1he script requires only
three positional parameters. An appropriate message is displayed it an incorrect number
ot parameters are entered.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named ProNIct-2 in your ,31)FMR directory, translate
the tolloving pseudocode into actual lines ot code, and then enter the appropriate
code into the Project6-2 script
Case num|erofpositionaiparameters
0. (ispia a messae inoi.atin hou to run the s.ript ano inoi.ate to
the user that no positionai parameters uere entereo.
1 or 2. (ispia a messae inoi.atin hou to run the s.ript ano
oispia the num|er of positionai parameters entereo.
'. (ispia the three positionai parameters.
Case Lise. (ispia an error inoi.atin that too man positionai
parameters uere entereo.
LnoCase
3. Save the script, and then quit the editor.
4. Make the script executable, and then execute the script vith no parameters.
3. Pecord the result.
6. Lxecute the script again vith one parameter, execute it again vith three
parameters, and then execute it once more vith tive parameters.
7. Pecord the results.
8. Close your vindov, and then log out.
,ERHWSR
4VSNIGX
6
4VoNecX 6-3
In this project, you vill implement the elif clause. A nonprotit organization, named
Helping Hands tor All, has hired several contract programmers to vork vith their
permanent programming statt. 1hey vant to give the employees, vho are hourly (sta-
tus ot H, or salaried (status ot S,, a s300 bonus. 1he programmers vith contractor
status (status ot C, vill not receive a bonus. Any other status is invalid.
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a shell script named ProNIct-3 in your $HOME/bin directory.
3. Insert the tolloving lines ot code
read -p "Enter Status: " Status
if $Status = "S" [[ $Status = "H" ]]
then
{{Bonus=500}}
echo "You get a bonus of" '$'$Bonus
elif $Status = "C" ]]
then
echo "You are a contractor. You need to become
permanent to receive a bonus."
else
echo "Invalid status"
fi
4. Save the script, and then quit the editor.
3. Make the script executable, and then execute the script tour times. Input S, H,
C, and 1 respectively, vhen prompted to enter status.
6. Pecord the output.
7. Close your vindov, and then log out.
4VoNecX 6-
In this project, you vill convert pseudocode that uses a decision structure into a shell
script. 1he script then vill accept three grades, calculate an average, and then display a
letter grade based upon the average.You vill need to use either the if statement or the
case statement to implement this script.
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a shell script named ProNIct-4 in your $HOME/bin directory.
3. Convert the tolloving pseudocode into code tor the script
Peao in three raoes from the ke|oaro
:erae the raoes
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
26 CLaTXeV 6 DecMsMoR SXVucXuVes
HaRHs-oR 4VoNecXs 27
(ispia the appropriate ietter raoe for the num|er raoe usin this s.aie.
90 to 100. (ispia a ietter raoe of `
80 to 89. (ispia a ietter raoe of P`
70 to 79. (ispia a ietter raoe of C`
to 9. (ispia a ietter raoe of (`
0 to 4. (ispia a ietter raoe of I`
Insert appropriate .omments
4. Save the script, quit the editor, and then make the script executable.
3. Lxecute the script and then input 100, 90, and 100 vhen prompted tor each grade.
6. Pecord the output.
7. Lxecute the script again. 1his time input 99, 8, and 70 vhen prompted tor
each grade.
8. Pecord the output.
9. Lxecute the script one last time. Input 80, 9, and 72 vhen prompted tor
each grade.
10. Pecord the output.
11. Close your vindov, and then log out.
4VoNecX 6-5
In this project, you vill convert pseudocode into a shell script and implement either an
if or case decision structure that determines the bonus level tor a salesperson.
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a shell script named ProNIct- in the $HOME/bin directory.
3. Convert the tolloving pseudocode into code tor the script
Peao :aiesIerson ano uarteri:aies from the ke|oaro
(ispia an appropriate messae rearoin the |onus uhen the
uarteri:aies for a :aiesIerson faiis uithin these ranes.
:er :1,000,000 :1,00 Ponus
:100,000 to :999,999 :70 Ponus
noer :99,999 ^o Ponus
4. Save the script, and then quit the editor.
3. Make the script executable, and then execute the script inputting MMkI vhen
prompted tor the salesperson and 7000 vhen prompted tor sales.
6. Lxecute the script again. Input Mar] vhen prompted tor the salesperson and
1000000 vhen prompted tor sales.
,ERHWSR
4VSNIGX
6
7. Lxecute the script one last time. Input LMsa vhen prompted tor the salesperson
and 20000 vhen prompted tor sales.
8. Pecord the output.
9. Close your vindov, and then log out.
4VoNecX 6-6
In this project, you vill apply conditional processing logic by vriting a shell script that
uses the if statement to accept one positional parameter trom the keyboard. It the para-
meter does not equal a value specitied in the script, display an invalid data error message.
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a shell script named ProNIct- in your $HOME/bin directory, and then
translate the program requirements into the appropriate code
lhe s.ript a..epts one positionai parameter
lhe s.ript :erifies a positionai parameter uas entereo, if not, a messae is oispiaeo
lhe positionai parameter is sa:eo as :tateCooe
If the positionai parameter is euai to ` or KY,` oispia a messae inoi.atin a :aiio
:tateCooe uas entereo
If the :tateCooe ooes not euai one of the pre:ious .ooes, oispia an error inoi.atin an
in:aiio :tateCooe uas entereo
Insert appropriate .omments
3. Save the script, and then quit the editor.
4. Make the scripts executable, and then execute the scripts using GA as the tirst
positional parameter.
3. Pecord the result.
6. Lxecute the scripts using OK as the tirst positional parameter.
7. Pecord the result.
8. Lxecute the scripts using KY as the tirst positional parameter.
9. Pecord the result.
10. Close your vindov, and then log out.
4VoNecX 6-7
1he goal ot this project is to turn a tlovchart into a shell script.
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named ProNIct-7 in your $HOME/bin directory.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
28 CLaTXeV 6 DecMsMoR SXVucXuVes
HaRHs-oR 4VoNecXs 29
3. Lsing the tlovchart shovn in ligure 6-21 as a guide, create the code that tultills
the program logic shovn there.
4. Pecord or print the script.
3. Lxecute the script inputting as A and 10 as B.
6. Pecord the result.
7. Lxecute the script again. Input as A and 4 as B.
8. Pecord the result.
9. Lxecute the script one last time. Input 3 as A and 10 as B.
10. Pecord the result.
11. Close your vindov, and then log out.
4VoNecX 6-8
In this project, you vill implement conditional processing and nest if statements. 1he
tirm named 1 Iiu 8 Associates needs a shell script vritten. 1he script needs to accept
tvo values, Status and Years. 1he status must be either S, H, or C (tor salary,
hour, and contract respectively,, othervise, an error message is displayed. An
employee vith a status ot H or S and vho has been employed tor at least tvo years
,ERHWSR
4VSNIGX
SLarL
GeL A and 8 rom
Lhe keyboard
A=5
Lnd
1rue
False
8>=10
1rue
False
Display "A equals 5
and 8 is reaLer Lhan
or equal Lo 10"
Display "A does noL
equal 5 and Lhe value
o 8 has noL been LesLed"
Display "A equals 5 buL
8 is less Lhan 10"
*MKuVe 6-21 FlowcharL or ProNecL 6-7
6
vill receive 30 shares ot company stock. A contractor vho has been vorking vith 1
Iiu 8 Associates tor more than three years vill receive a s100 bonus. An appropriate
message must be displayed tor employees or contractors not meeting the requirements.
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a shell script named ProNIct-8 in your $HOME/bin directory.
3. Insert the tolloving lines ot code
read -p "Enter Status " Status
if $Status = "S" [[ $Status = "H" [[ $Status = "C" ]]
then
read -p "Enter Years " Years
if $Status = "S" [[ $Status = "H" ]]
then
if $Years -ge 2 ]]
then
{{NumOfShares=50}}
echo "You get a bonus of" $NumOfShares "shares
of company stock"
else
echo "You must be here at least 2 years for
receiving company stock."
fi
elif $Status = "C" ]
then
if $Years -gt 3 ]]
then
{{Bonus=100}}
echo "You get a bonus of" '$'$Bonus
else
echo "You must be here at least 3 years for
receiving company stock."
fi
fi
else
echo "Invalid status"
fi
4. Save the script, and then close the editor.
3. Make the script executable, and then execute the script. Input H vhen prompted
tor status and vhen prompted tor years.
6. Pecord the output.
7. Lxecute the script again. Input C vhen prompted tor status and 2 vhen
prompted tor years.
8. Pecord the output.
250 CLaTXeV 6 DecMsMoR SXVucXuVes
Case 4VoNecXs 251
9. Lxecute the script again. Input S vhen prompted tor status and 1 vhen
prompted tor years.
10. Pecord the output.
11. Lxecute the script one last time. Input 1 vhen prompted tor status.
12. Pecord the output.
13. Close your vindov, and then log out.
'AS) 46OJ)C8S
Case 6-1
1MI has asked you to create a script that vill allov the user to enter one ot several
choices trom the command line. 1he only alloved choices are as tollovs
1. Copy one tile to another. Allov the user to enter a source tilename to copy. It the
source tile exists, read the name ot the destination tile and copy the tile. Display a
message indicating success or tailure based on the return status.
2. Pemove a tile it it exists. Display a message indicating success or tailure based on
the return status.
3. Display only the current day ot the veek.
4. Display a calendar.
Case 6-2
Wendy 1ran-Patel ovns Working Out lor lun, Inc., and vants to create a revards
contest tor her customers. She hires you to help develop the revards program as vell as
implement it. She vould like to give three revards each month.1here vill be a s23 movie
pass, a s30 restaurant gitt certiticate, and a s100 cash prize.You are required to propose the
method ot determining the revard, and vrite a script to meet your proposal.1he methods
used to determine the revard can be based upon total number ot minutes on a treadmill
machine, total pounds litted, or total number ot aerobic vorkout classes attended.You need
to determine appropriate levels tor each prize. You must create a tlovchart or prepare
pseudocode tor your proposal, and then implement your proposal in a script that displays
the revard given.
'EWI
4VSNIGX
'EWI
4VSNIGX
6
253
',%48)6

0334-2+ 7869'896)7
-RXLMWGLETXIV]SY[MPP
9RHIVWXERHPSSTXLISV]
9RHIVWXERHXLIwhile WXEXIQIRX
9RHIVWXERHXLIuntil WXEXIQIRX
9RHIVWXERHXLIfor WXEXIQIRX
%
lthough shell scripts statements are executed sequentially, you can change
the tlov vithin the script by implementing looping structures. Iooping
structures allov your scripts to repeatedly execute the same set ot statements
tor ditterent data as long as some specitied condition exists. Once the condi-
tion no longer exists, processing continues to the statements tolloving the
looping structure. In this chapter, you vill learn about the shell`s implemen-
tation ot looping structures using the while, until and for commands.
9NDRS1ANDING 0OOP 8HORY
In programming theory, a loop is vhen a condition causes a specitic set ot program-
ming statements to be repeated. 1he statements vithin the loop repeat until another
condition occurs vhich then terminates the loop.1he term iteration, or pass, reters to
each completion ot the statements vithin a loop, theretore, it a loop repeats its state-
ments three times, it has completed three iterations, or passes.
1he tlovchart in ligure 7-1 shovs the general torm ot the basic looping structure.You
can see that a set ot statements is executed prior to the condition being tested. It the con-
dition tests true, then the program repeats the statements prior to the decision. It the
condition tests talse, the program does not repeat the steps, and subsequent statements
continue to execute as normal.
1he biggest advantage ot using looping structures is that they allov you to enter data
vithout knoving hov much data needs to be entered. lor example, a bank may need
to process thousands ot transactions in customer accounts. A program can be created to
read all ot the records and process them.When there are no more records to read in the
tile, the loop terminates. Similarly, a teacher may need a program that calculates grades.
Because the number ot grades the teacher needs to enter may vary, a program can be
created using loops to prompt the teacher tor each grade. Once all grades are entered,
the loop terminates and calculates the grade.
SLaLemenLs
1esL
condiLion
SLaLemenLs
1rue
False
SLaLemenLs
fIgure 7-1 FlowcharL o a loop
254 Chapter 7 LoopIng Structures
UnderstandIng Loop 1heory 255
ligure 7-2 shovs a more complex example that contains more than one loop. A loop
allovs code to repeatedly execute until a condition exists. Sally Mingledort `s Ice
Cream 8 Cones, Inc. Main Menu page allovs users to access a variety ot other sub-
menus. A menu uses looping structures to allov the menu selections to continually
appear on the screen. Once users choose other menu items, another loop tor the sub-
menu executes alloving users the ability to choose selections on the submenu. When
users are tinished vith the submenu, they can return to the menu on vhich they
started. Here they can go back into the submenu or go into other submenus vhich
are also made ot looping structures. It is the loop that tacilitates the ability to go back
and torth betveen menus.
CusLomer DeLail Nenu
1. Add CusLomer
2. DeleLe CusLomer
3. Nodiy CusLomer
4. ReLurn Lo Nain Nenu
Sally Ninledor's lce Cream & Cones, lnc.
Nain Nenu
1. CusLomer DeLail
2. AccounLin
3. Orders
4. Payroll
5. Suppliers
LnLer your selecLion:
AccounLin Nenu
5. AccounLs Receivable
6. AccounLs Payable
7. General Leder
8. ReLurn Lo Nain Nenu
Order Nenu
9. CusLomer Purchases
10. CusLomer ReLurns
11. Orders in Suspense
12. ReLurn Lo Nain Nenu
fIgure 7-2 Nenu sysLem LhaL uses loops
7
An InfInIte Loop
Sometimes the logic ot your program can cause the program to go into vhat is called an
intinite loop. An infinite loop is a loop that theoretically repeats vithout end. It does not
stop unless you terminate the script`s process.You can terminate a script vith a kill signal.
One disadvantage ot a script going into an intinite loop is that it consumes an excessive
amount ot processing time.You can test this yourselt by opening up tvo vindovs. In one
vindov, run the yes command and in the other run the top command. ligure 7-3 and
ligure 7-4 shov the betore and atter System Monitor screens tor the yes command
running and consuming all ot the CPL time, and then being terminated. Notice the line
zigzagging in the CPL Lsage History section ot the System Monitor vindov
shovn in ligure 7-3. Lach ot the horizontal lines running across the background rep-
resents a 20 increment. You can see that utilization started ott lov because the yes
command had not been started yet. Hovever, once the command is started, you can see
the utilization rise and plateau at the 100 mark. At the time the screenshot vas taken,
the utilization rose to 101.00. 1he act ot taking the screenshot is CPL intensive, too.
1he reason that the utilization exceeds 100 is that this is an average time.
fIgure 7-3 An ininiLe loop consumin CPU uLilizaLion
256 Chapter 7 LoopIng Structures
UnderstandIng the [LMPI Statement 257
Notice, in ligure 7-4, that the CPL utilization dropped to 11 atter the yes command
is terminated by pressing CtrlC.
9NDRS1ANDING 1H [LMPI 71A1MN1
1he theoretical 1hiie statement tests vhether a condition is true or talse. It the condition
is true, the 1hiie statement repeats the instructions, tolloving the Do clause up to the
Lno1hiie clause. It the condition is talse, the loop terminates and program tlov contin-
ues subsequent statements. 1he logic ot the 1hiie statement is
1hiie true.onoition
Do
Ierform a.ti:it for true.onoition
Lno1hiie
ligure 7-3 shovs a tlovchart depicting the 1hiie statement. 1he shaded area represents
the 1hiie loop.
fIgure 7-4 1erminaLin an ininiLe loop causes CPU uLilizaLion Lo drop
7
Consider the tolloving business application structured using the pseudocode tor the 1hiie
statement. In this example, the 1hiie loop is used to process multiple records in a tile.
pen fiie
1hiie ou ha:e re.oros
Do
Peao re.oro
Iro.ess re.oro
1rite re.oro
Lno1hiie
Ciose fiie
Notice that tirst the tile containing the records is opened. 1hen, as long as you have
records in the tile, they are read and then processed. A record must be read prior to pro-
cessing it. Processing a record might include pertorming computations or logic opera-
tions on the tields vithin the record. As long as there are records in the tile, they are read
and then processed. Once the loop terminates, the tile is closed.
ls While
condiLion
Lrue?
LxecuLe sLaLemenLs ollowin
Lhe While sLaLemenL
Yes
No
LxecuLe sLaLemenLs precedin
Lhe While loop
Do sLaLemenLs wiLhin
Lhe While loop
fIgure 7-5 FlowcharL o Lhe ;LMPI sLaLemenL
258 Chapter 7 LoopIng Structures
UnderstandIng the [LMPI Statement 259
1he [LMPI Statement Syntax
Iike the theoretical 1hiie statement, the shell`s while statement also tests tor a condi-
tion being true or talse, and it the condition is true, pertorms the loop`s statements, it talse,
it bypasses the loop`s statements. 1he while loop in the shell takes the tolloving torm
while 11stA
do
11stS
done
1he 11stA statements are a set ot commands that is executed and that results in an exit
status. It the commands in 11stA exit vith an exit status ot zero, then the commands
in 11stS are executed. It the commands in 11stA exit vith a nonzero exit status, the
commands in 11stS are not executed. 1he statements tolloving done are executed
vhether or not commands in 11stS execute.
1o prove that the while command pertorms the do statements as long as the exit status
is zero, run this command
while true
do
echo $?
done
1he statement true alvays returns an exit status ot zero. It displays the value zero an
intinite number ot times.You can terminate this statement or any other intinite loop by
pressing CtrlC.
You can accomplish Lhe same proo by enLerin Lhis command: while !
false, do echo $?,done. 1he sLaLemenL false always reLurns an exiL
sLaLus o one. However, by placin Lhe neaLion operaLor ( ! ) prior Lo iL, Lhe
condiLion is zero. 1his loop displays Lhe value zero an ininiLe number o Limes.
UsIng the [LMPI Statement
You can use the while statement to test tor characters. Consider the script shovn in
ligure 7-6. In this script, a listing ot the users vho are logged on as vell as a listing ot
current tiles are displayed. 1he script user is then prompted as to vhether he vould like
to stop the script once the netvork intormation is displayed. It the user enters a Y, then
the script terminates, othervise, the loop continues. Iet`s look at this in closer detail.
In the WhileIoopStop script a variable named Stop is initialized to N. Next, the
while statement uses the logical negation operator to determine it the variable is not
equal to Y. 1he tirst time through, the variable named Stop is equal to N, so the
while condition tests true. Because it tests true, the do statements are executedthese
are the who, ls, and read statements.1he user is then prompted by the read statement
tor an ansver. It the user enters anything but a Y, the while loop continues.
8MT
7
It is important to understand hov to use the while loop to test tor character values
because there may be times vhen you need to do just that. lor instance, you may need
to loop through code to prompt users to enter certain values, and then test their input.
Or, you might need to create a script that repeatedly asks the user to enter a valid pass-
vord. Next you vill create a script that tests a condition. It the condition is true, then
the while loop vill display a listing ot processes using the ps~e]more command,
and then prompt the user to continue.
1o create a script using while to test character values:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation
vindov.
2. Create a script named WhileLoopB in the $HOME/bin directory.
3. Insert the tolloving lines ot code to create a loop vhich shovs the processes
that are running
Continue=Y
while $Continue = "Y" ]]
do
ps~e[more #The"-e"optionshowsall
processes.
read~p"Doyouwanttocontinue?{Y}"Con
Continue=`echo$Con[tr:lower:]:upper:]`
#Convertanswertouppercaseandtestthat.
done
fIgure 7-6 WhileLoopSLop scripL LhaL LesLs or characLers
260 Chapter 7 LoopIng Structures
UnderstandIng the [LMPI Statement 261
4. Save the script, and then quit the editor.
3. Make the script executable, and then execute the script. A listing ot all
processes is displayed.
6. When prompted, enter Y, and then press Lnter. Because you ansvered Y,
a listing ot all processes is displayed again.You are prompted again.
7. 1his time vhen prompted, enter N, and then press Lnter. Because you
ansvered N, the script terminates.
8. Close your vindov, and then log out.
1he [LMPI Statement and Command xIt Status
You can use the while statement to test the exit status ot a command. Why vould you
vant to do this 1esting the exit status ot a command in a while statement is usetul tor
determining vhether or not a command succeeded or tailed. Once you determine the
exit status, you can pertorm iterations based on that knovledge. See the tolloving script
while ! cp fileX.txt fileY.txt
do
echo "Attempting to copy."
sleep l0 # Pause the script for l0 seconds.
done
In this example, the while statement attempts to copy a tile. It the tile is present, it is
copied. It the tile does not exist, the while statement loops continually until the tile
gets created. Notice that the negation operator ( ! , is used. 1he while statement
negates the exit status ot the cp fileX.txtfileY.txt command, thus the copy
command tails it tileX.txt is nonexistent. 1his results in a nonzero exit status.1he nega-
tion operator turns that status to a zero, tor true. As long as the while ! cp
fileX.txtfileY.txt is true the tile is never copied. As part ot the while loop, a
message is displayed indicating that the script vill attempt to copy the tile again. 1he
script pauses tor 10 seconds so you have time to read the message. 1he script continues
to try to copy the tile as long as tileX.txt is not present. Once the tile is created, it is
copied to tileY.txt and the script terminates. It is possible tor the tile to be created by a
background program or by you using another 1erminal emulation vindov. ligure 7-7
shovs the WhileCopy script running.
Notice that there are tvo vindovs in ligure 7-7. In the vindov on the lett, you can
see the contents ot WhileCopy and its execution. You can see that it is attempting to
copy the tile but cannot do so because it did not exist at the time the script vas exe-
cuted. Hovever, in the terminal vindov on the right in ligure 7-7, you can see that the
tile, tileX.txt, is created using the touch command. It is important to understand that
the script in the lett vindov vas started betore tileX.txt vas created. Once tileX.txt is
created, the script copies tileX.txt to tileY.txt.
7
1ermInatIng a Loop
1here may be times vhen you need to terminate a loop betore a condition terminates
the loop, tor instance, it you vanted your loop to terminate prematurely because the
script encountered an error vithin the loop or a user decided to exit a menu that uses
a loop. In these cases, you can use the break command to end the loop.1his command
is used vithin the shell`s looping structures and is otten accompanied by a variable count.
Consider the tolloving code
{{count=l||
while true
do
echo $count
{{count++||
if $count ~gt 3
then
break
fi
done
In this example, the while statement tests tor a zero exit status. As you knov, the true
command alvays returns a zero exit status. You then set a variable count to increment
and test it the variable`s value is greater than three. Once the variable is greater than
three, the break command is activated, causing the loop to terminate. 1hen, control ot
the script is passed to any statement tolloving the break clause.
fIgure 7-7 1he WhileCopy scripL, iLs ouLpuL, and anoLher 1erminal emulaLion window
used Lo creaLe a ile
262 Chapter 7 LoopIng Structures
UnderstandIng the [LMPI Statement 263
1here may be Limes when you wanL Lo exiL jusL one iLeraLion o Lhe loop
insLead o LerminaLin Lhe whole loop. ln Lhis case, you would use Lhe
continue sLaLemenL.
NestIng [LMPI Loops
1he shell also allovs you to nest while statements to create a loop vithin a loop. One
reason you might consider using a nested while loop is to create a menu that uses the
while statement to repeatedly display available options. You could then embed the
case statement vithin the while statement to handle those options. Also, you could
set it up so that one ot the options has a loop that requires a specitic value to be entered
and that displays the same prompt it the correct value is not entered. 1hus, you end up
vith the menu loop, and vithin it, a nested loop that prompts tor a certain value.
ligure 7-8 depicts hov nested loops tit together, as vell as hov you structure the syn-
tax tor those loops.
whilePMWX
do
whilePMWX
do
whilePMWX
do
PMWX
done
PMWX
done
PMWX
done
1his is Lhe ouLermosL loop; once iL
compleLes, all o Lhe loops iL conLains
will have compleLed
1his is Loop 2; iL compleLes all o iLs
iLeraLions beore Lhe ouLermosL loop
compleLes jusL one o iLs iLeraLions
1his is Lhe innermosL loop; iL will compleLe
all o iLs iLeraLions beore Loop 2 compleLes
jusL one o iLs iLeraLions
fIgure 7-8 UndersLandin nesLed loops
8MT
7
In ligure 7-8 there are three loops. 1he innermost loop`s condition is reached betore
Ioop 2`s condition is reached. Ioop 2`s condition is reached betore the outermost loop`s
condition is reached. In other vords, each loop completes all ot its iterations betore the
loop surrounding it goes through only one ot its iterations.
When nesLin loops, i you have jusL Lwo loops, Lhe one embedded inside Lhe
oLher is called Lhe inner loop. 1he oLher is called Lhe ouLer loop. When you
have more Lhan one nesLed loop, Lhe addiLional loops are reerred Lo as "Loop
Nom/er," where Nom/er is Lhe number o Lhe loop beinnin rom Lhe ouLer
loop. For example, i you have Lhree loops, you would have Lhe ouLer loop,
Loop 2 and Lhen Lhe inner loop.
ligure 7-9 shovs an example ot nesting while loops. 1he WhileNest script contains
tvo loops. On the tirst pass ot the tirst vhile loop, called the outer loop, the condition
$x~le3 is tested. It x is less than three, then the second while loop, the inner loop,
is tested. 1his is vhere the condition $y ~le 3 is tested. As long as y is less than
three, then the variables are displayed using the statement echo $x $y. 1hen, y is
incremented vith the statement {{y++||. Once y reaches three, then x is incre-
mented using {{x++||. At this point, the inner while statement has made three com-
plete iterations. Meanvhile, the outer loop has only made one. So, the outer loop makes
one iteration, and the inner loop makes iterations until x tinally reaches three, and the
script terminates. 1he inner while loop then displays the values 1, 2, 3 tor every one
occurrence ot x.
fIgure 7-9 A scripL usin nesLed [LMPI sLaLemenLs
8MT
264 Chapter 7 LoopIng Structures
UnderstandIng the [LMPI Statement 265
1he result ot the WhileNest script`s execution displays the x variable in the tirst, or
lett, column and the y variable in the second, or right, column. Notice that the y
variable changes three times tor every one change ot the x variable. In total, the variables
are displayed nine times. In this example, you can multiply the tvo numbers in each
condition, (in this case, three multiplied by three, to determine hov many times the
inner loop passes through its do statements.
Next you vill implement the code in ligure 7-10 to help you understand hov to nest
while statements. 1he variables used in this example, outer and inner, are used tor
incrementing and testing the iterations ot the nested loops.
1o create a script using nested while statenents:
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named WhileLoopNest in the $HOME/bin directory.
3. Insert the tolloving lines ot code to use tvo while statements to implement
nested loops
{{outer=1}}
while $outer -le 3 ]]
do
{{inner=1}}
while $inner -le 3 ]]
do
echo $outer $inner
{{inner++}}
done
{{outer++}}
done
4. Save the script, and then quit the editor.
3. Make the script executable, and then execute the script. 1vo columns ot
numbers appear, they are the contents ot the variables outer and inner. See
ligure 7-10. 1he tirst column represents the change ot the variable outer
vithin the outside loop. 1he second column represents the change ot the
variable inner vithin the inside loop. Notice that inner changes three times as
otten as outer because it is incremented in the inner loop.
6. Close your vindov, and then log out.
7
9NDRS1ANDING 1H YRXMP 71A1MN1
Iike the theoretical 1hiie statement, the ntii statement also tests vhether a condition
is true or talse. 1he ntii statement repeats statements until a condition becomes true.
1hink ot the ntii statement as the opposite logic ot the 1hiie statement. 1he logic ot
the ntii statement is shovn belov
ntii faise.onoition
Do
Ierform a.ti:it for faise.onoition
Lnontii
ligure 7-11 shovs a tlovchart displaying the ntii statement.
fIgure 7-10 1he WhileNesLedLoop scripL and a sample run
SLep 5: resulLs o
execuLion o scripL
266 Chapter 7 LoopIng Structures
UnderstandIng the YRXMP Statement 267
Pecall the pseudocode tor the 1hiie statement used to process records. Nov, you vill
see hov to turn the 1hiie statement into the equivalent ntii pseudocode. When using
the ntii statement, you need to rephrase the condition. In this case, the condition being
tested is, Are there any more records It there are more records, process them. Once
there are no more records, terminate the loop, and close the tile.
pen fiie
ntii there are no more re.oros
Do
Peao re.oro
Iro.ess re.oro
1rite re.oro
Lno1hiie
Ciose fiie
ls Until
condiLion
Lrue?
LxecuLe sLaLemenLs ollowin
Lhe Until sLaLemenL
No
Yes
LxecuLe sLaLemenLs precedin
Lhe Until loop
Do sLaLemenLs wiLhin
Lhe Until loop
fIgure 7-11 FlowcharL o Lhe 9RXMP sLaLemenL
7
Because the logic ot ntii can be a bit tricky, consider one more section ot pseudocode
tor the ntii statement to help you get a better idea hov it vorks. 1ake a look at an
example that has happened to youvhat to do on a rainy day.
In this example, as long as it is raining, you vill stay indoors. Once it stops raining the
condition turns talse, and the loop terminates.1hen, you can do an outside activity, such
as vashing the car or planting vegetables, in this case. Here is the pseudocode
ntii it stops rainin
:ta insioe
Lnontii
1ash .ar or piant :eeta|ie aroen
Nov, here`s the rainy day pseudocode tor the ntii statement converted into the 1hiie
statement, so you can compare the tvo. Notice that the logic ot the tvo statements is
just the opposite.
1hiie it is rainin
:ta insioe
Lno1hiie
1ash .ar or piant :eeta|ie aroen
1he YRXMP Statement Syntax
Whereas the while statement pertorms its do statements it the exit status ot the con-
dition or list is a zero or true, the until statement pertorms its do statements it the exit
status ot the condition or list is nonzero, or talse. 1he until statement syntax is
until 11stA
do
11stS
done
Like Lhe while sLaLemenL, you can also wriLe Lhe until sLaLemenL as a sinle
sLaLemenL, as in: untilPMWX%,doPMWX&,done.
8MT
268 Chapter 7 LoopIng Structures
UnderstandIng the YRXMP Statement 269
1he 11stA statements are a set ot commands that is executed vith an exit status. It the
commands in 11stA result in a nonzero exit status, then the commands in 11stS are
executed. It the commands in 11stA result in an exit status ot zero, the commands in
11stS are not executed. In either case, the program tlov continues normally atter the
done clause.
As you sav vith the while statement, you can prove this by running the tolloving
command
until ! true
do echo $?
done
1his command displays the value one an intinite number ot times. You can terminate
this statement by pressing CtrlC.
You can accomplish Lhe same proo by enLerin Lhis command: until
false,doecho$?,done, which also displays Lhe value one an ininiLe
number o Limes.
UsIng the YRXMP Statement wIth LogIcal OperatIons
Pecall the script named WhileIoopStop that continually displays the logged-in netvork
users and then prompts to see it the script user vould like to continue. Consider hov
this script might tunction it you modity it to use the until statement. As long as the
user does not enter a Y, the script loops, displaying the currently logged-in users.
Notice that the original code tor WhileIoopStop has been slightly moditied to shov
you hov this script vorks using the until statement and that it has been renamed the
LntilIoopStop script
Stop=N
until $Stop = "Y"
do
who ls
read ~p "Do you want to stop? {Y|" Stop
done
echo "Stopping."
ligure 7-12 displays the LntilIoopStop script.You can see that the script continues to
display the contents ot a directory until the user presses Y to stop it.
8MT
7
Consider the tolloving example. Say you vork as a shell programmer in the Intormation
1echnology Department tor Plane Parts, Inc., a manutacturer that produces a generic line
ot tools used tor airplane maintenance. 1he production manager requires employees to
till out a daily timesheet tor the previous day`s activities. Hovever, most ot the time,
employees are days late in tilling out the timesheet. She requests your help eliminating
the timesheet delay. Next you vill vrite a script to remind employees to complete their
timesheets each day. 1he script runs tor the tirst tive minutes ot each hour, unless it is
terminated. In the script, the variable minute contains the minute derived trom the date
command using the cut command. As long as the current system`s minute is less than
tive, then the until loop pertorms an iteration. With each iteration, a message is dis-
played indicating the user should complete the daily timesheet, a pause ot 13 seconds
occurs, and then the current minute is derived again. Lntil the nevly determined minute
becomes greater than or equal to tive, an iteration occurs.
1o create a script using the until statenent:
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named 1ineSheet in the $HOME/bin directory.
fIgure 7-12 1he UnLilLoopSLop scripL and iLs ouLpuL
270 Chapter 7 LoopIng Structures
UnderstandIng the YRXMP Statement 271
3. Insert the tolloving lines ot code to create a message that asks the employee
to complete a daily timesheet and displays the message until tive minutes atter
the hour in vhich the script is run.
declare -i minute
minute=`date +%M`
until $minute -ge 5 ]]
do
echo "Complete daily timesheet!"
sleep 15
minute=`date +%M`
done
4. Save the script, and then quit the editor.
3. Make the script executable, and then execute the script to check that it runs
correctly. 1o implement this script, you vould add this to one ot the login
tiles discussed in Chapter 3. (^ote lor this to vork properly, your system
time must be betveen 0 and 3 minutes past any given hour., You can either
vait tor the time to meet this requirement or, vithin the script, change 3
to 10 tor minutes trom your current time so the script vill vork vith the
current time on your system. See ligure 7-13. Notice that three messages
appear on the screen. As long as the minute is less than or equal to tive, the
message Complete daily timesheet' is displayed. Once the minute exceeds
tive, the message is no longer displayed.
6. Close your vindov, and then log out.
fIgure 7-13 1he 1imeSheeL scripL
SLep 5: Lhree messaes
appear as resulL o scripL
7
Consider one more example. Plane Parts, Inc. vants you to create a script that checks
to see it the nightly run tor the Accounting program tailed. It it did, an error tile is auto-
matically created by the program. Also it`s important to note that it the nightly run did
tail, the application that generated the error vill not restart because ot the error, and this
results in other users being unable to do their vork. Next, you vill create a script that
continually displays a message indicating that an error tile exists resulting trom an error
in the Accounting program. 1he error tile should not be removed betore an investiga-
tion determines the reason tor tailure. It the tile exists, then an error must have occurred.
You can use the until loop to determine it the error tile does exist, and it it does, then
generate messages indicating just that. Have the loop continue until the tile no longer
exists. In the until statement, the ~e option returns true it the tile exists. 1his condi-
tion is negated vith the ! operator.
ln eneral, iL is noL uncommon or iles Lo eL processed overnihL, and i Lhe
proram processin Lhe iles ails, a SysLem AdminisLraLor is usually conLacLed
and an error ile is leL.
1o create a script using the until loop to test the eistence of a file:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation
vindov.
2. Create the NightlyRunLrror.tt tile in your $HOME/bin directory.
3. Create a script named UntilFile in the $HOME/bin directory.
4. Insert the tolloving lines ot code to display a message indicating that an error
tile exists and needs to be deleted betore the Accounting program can run.
Note the code does not remove the script because the programmer or
System Administrator needs to investigate the reason tor the tailure. When the
tile is ultimately removed, then the loop terminates, and the Accounting pro-
gram can be restarted.
until ! ~e NightlyRunError.txt
do
echo "The NightlyRunError.txt file exists and
it needs to be deleted in order to run the
Accountingprogram."
sleep 3
done
echo "Starting Accounting program..."
# The full path to accounting program would go here.
3. Save the script, quit the editor, and then make the UntilFile script executable.
6. Lxecute the script. See ligure 7-14. A message appears indicating the tile
exists and must be removed in order tor the Accounting program to run.
8MT
272 Chapter 7 LoopIng Structures
UnderstandIng the JSV Statement 273
7. Open another 1erminal emulation vindov, and then remove the
NightlyRunLrror.tt tile so you can see vhat happens vhen the tile is
not present.
8. Lxecute the script again. See ligure 7-14. 1he message Starting Accounting
program. appears on the screen because the NightlyPunLrror.txt tile is
not present.
9. Close your vindovs, and then log out.
9NDRS1ANDING 1H JSV 71A1MN1
1he 1hiie and the ntii statements are usetul vhen you do not knov hov much data
you have to process. 1here is another logical looping structure, the Ior statement, that
allovs you to process a set number ot iterations.
Iook at the general torm ot the theoretical Ior statement
Ior :aria|ie oes from initiai:aiue to enoin:aiue
Do
Ierform a.ti:it as ion as :aria|ie is not euai to the enoin:aiue
In.rement or De.rement :aiue of :aria|ie
LnoIor
fIgure 7-14 1he UnLilFile scripL
SLep 6: messaes indicaLin
ile has noL been removed
SLep 8: new messae
because ile is no
loner presenL
7
1he Ior loop begins vith a starting value tor a :aria|ie. 1he starting value is set vith
initiai:aiue. 1hen, the statements in the loop body are executed. Atter that, the :aria|ie
is changed, it is either incremented or decremented. 1he Do statements are repeatedly
executed until the :aria|ie reaches the enoin:aiue. ligure 7-13 shovs a tlovchart dis-
playing the Ior statement.
Iet`s look at an example. In the tolloving pseudocode, the variable x starts at one, the
contents ot x are displayed, and then x is incremented by one. 1he loop repeatedly
ls varia/le <=
enJing-valoe
LxecuLe sLaLemenLs ollowin
Lhe lor sLaLemenL
Yes
No
lniLialize varia/le Lo initial-valoe
SLaLemenLs precedin Lhe lor loop
Do sLaLemenLs wiLhin
Lhe lor loop
lncremenL/decremenL
varia/le
fIgure 7-15 FlowcharL o Lhe *SV sLaLemenL
274 Chapter 7 LoopIng Structures
UnderstandIng the JSV Statement 275
displays the contents ot x and increments x until x equals the number tive. Here
is the pseudocode
Ior x in 1 to
Do
Dispia x
LnoIor
You can also decrement by tolloving the same logic. In this case, the variable x starts
at tive, displays x, and then automatically decrements x by one until it reaches one.
1he pseudocode tor decrementing a variable is
Ior x in to 1
Do
Dispia x
LnoIor
1he JSV Statement Syntax
1he advantage ot the for statement is that it allovs you to control the number ot iter-
ations a loop pertorms. Iet`s say you vork tor a small radio station, and the on-air mete-
orologist vants you to take the average ot last veek`s outside temperature.You could use
the for statement to loop through seven iterationsone tor each day ot the veek. Or,
in another scenario, it you vant to tind the average ot tive grades tor your Advanced
Programming class, then you can use a for statement to complete this task.
1here are tvo variations ot the for statement.
Lsing for vith a vord list
Lsing for vith an arithmetic expression
You can place both torms on a single line, using semicolons, or on separate lines. 1he
syntax ot the tvo variations is covered in the tolloving sections.
UsIng JSV wIth a Word LIst
You use the vord list version ot the for statement to loop through items in a vord list.
It is not used tor controlling a numeric variable in the vord list and incrementing or
decrementing it. 1he arithmetic expression torm ot the for statement does that. Iet`s
look at an example vhere the for statement is pertormed tive times
for number in l 2 3 4 5
do
echo$number
done
7
With the statement for number in l 2 3 4 5, the variable named number is
assigned to the tirst item in the list, vhich is 1.1he statement betveen the do and done
clauses is pertormed tor each assignment ot the variable. Next, the value ot the variable
named number changes to each item in the list until the last item is reached.
Lssentially, number is set to 1, then the do statements are executed, then number is set
to 2, and the do statements are executed again, and so on until the variable number
equals the last item in the list, in this case 3. 1he do statements are pertormed tor the
last item. 1he numbers are displayed one at a time on one line each.
1he variable name is a user-detined name.1he items in the vord list do not have to be
numeric. Next you vill create a script that uses characters instead ot numbers in the
vord list.
1o create a script using for vith a vord list:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation
vindov.
2. Create a script named WordList in the $HOME/bin directory.
3. Insert the tolloving lines ot code to create a script that makes use ot a for
loop to insert items, in this case various truits, in a vord list
for fruit in pear banana peach
do
echo"Ineeda$fruitfromthestore."
done
4. Save the script, and then quit the editor.
3. Make the script executable, and then execute the script. 1hree statements
appear indicating that a pear, banana, and peach are needed trom the store.
6. Close your vindov, and then log out.
UsIng ArIthmetIc OperatIons
You can also pertorm arithmetic operations on the vords in the vord list as long as they
are numbers. lor example, consider the tolloving lines ot code
for var in 2 4 6 8
do
{{power = $var ** 2||
echo $var "to the second power is" $power
done
In this example, the variable named var is assigned to a number2, 4, 6, 8, in the vord
list. In the tirst iteration, var is set to 2.1hen, inside the loop, the variable named pover
is equal to the value ot var, vhich is 2, to the second pover, using **2, in the third line.
1hen, a message is displayed indicating that 2 to the second pover is 4.
276 Chapter 7 LoopIng Structures
UnderstandIng the JSV Statement 277
1his repeats tor the values in the vord list. 1he output is tour lines and indicates that 2
to the second pover is 4, 4 to the second pover is 16, 6 to the second pover is 36, and
tinally, 8 to the second pover is 64.
Next you vill create a loop that vill allov you to enter seven daily temperatures and
display their average.
1o create a script using for to enter a specific nunber of tenperature values:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation
vindov.
2. Create a script named ForAvg in the $HOME/bin directory.
3. Insert the tolloving lines ot code to create the loop that iterates seven times
fornumin1234567
do
4. Insert the tolloving lines ot code to read the temperature values, accumulate
the value in a variable named 1emp1otal, and then terminate the loop. 1he
accumulation is done because on the next pass ot the loop, the current value
ot 1emp changes to the next temperature reading.
read-p"EnterDailyTemperatureforday$num:"Temp
{{TempTotal=$TempTotal+$Temp}}
done
3. Insert the tolloving lines ot code to calculate and display the average
#After$numreaches7,averagethetemperaturesand
displaytheaverage.
{{AvgTemp=$TempTotal/$num}}
echo"Averageweeklytemperaturewas:"$AvgTemp
6. Save the script, and then quit the editor.
7. Make the script executable, execute the script, and then enter the tolloving
seven temperatures vhen prompted 100, 90, 88, 102, 91, 97, and 95. See
ligure 7-16. A message is displayed indicating that the average veekly tem-
perature vas 94.
8. Close your vindov, and then log out.
7
UsIng JSV wIth an ArIthmetIc xpressIon
Lsing a for loop vith an arithmetic expression allovs you greater control over the loop
by initializing, testing, and changing a numeric value.1he for loop uses a control vari-
able to determine the number ot loop iterations. 1here are three parts to this type ot
looping structure. 1hey are
Initialize the loop`s control variable vith exress1on1
1est a conditional operation vith exress1on2
Change the loop`s control variable vith exress1on2
Consider the tolloving example
for{{num=l,num<=5,num++||
do
echo$num
done
In this example, exress1on1 is num=l, exress1on2 is num<=5, and exress1on2
is num++. Here is hov it vorks. 1he variable num is initialized to a starting value in the
tirst expression. 1hen, the value ot num is compared to tive. It num is less than or equal
to tive, as shovn in exress1on2, then the command(s, in the do11st are executed.
linally, the variable is incremented in exress1on2.1hen the test starts all over. In this
example, the loop continues until the value ot the variable num exceeds tive. 1he exe-
cution ot this script causes the numbers 1 through 3 to appear one atter the other on
separate lines in one column.
fIgure 7-16 1he ForAv scripL and iLs ouLpuL
SLep 7: LemperaLure
averae is displayed
278 Chapter 7 LoopIng Structures
UnderstandIng the JSV Statement 279
Consider vhat happens it you modity the lorAvg script by combining the read command
vith the arithmetic expression torm ot the ot for statementyou create a very tlexible
script. Here you have the number ot days ot temperatures to be entered determined by the
user. Here is the code tor the lorNum script vhich is based on the lorAvg script
read~p"Enterthenumberofdays:"Days
for{{num=l,num<=$Days,num++||
do
read~p"EnterDailyTemperatureforday$num:"Temp
{{TempTotal=$TempTotal+$Temp||
done
{{AvgTemp=$TempTotal/{$Days|||
echo"Averageweeklytemperaturewas:"$AvgTemp
1his script allovs the user to enter any number ot days tor vhich temperature averages
are taken. See ligure 7-17. Here the user enters the numeral 4 tor the number ot days,
and then inputs the temperatures to obtain the average tor those days. 1here is also
another run vhere the user enters temperatures tor tvo days that are also averaged.You
could not do this using the logic in the lorAvg script created in the last exercise.
Next you vill create a for loop, increment the variable num, and use the mathematical
operation tor squaring the number.
fIgure 7-17 1he ForNum scripL and iLs ouLpuL
7
1o create a for loop script using epressions:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation
vindov.
2. Create a script named SquareLoop in the $HOME/bin directory.
3. Insert the tolloving lines ot code
for {{num=1,num<=10,num++}}
do
{{sguared=$num**2}}
echo$sguared
done
4. Save the script, and then quit the editor.
3. Make the script executable, execute the script, and then record the output.
1he numbers 1 through 10 are squared and the result is displayed.
6. Close your vindov, and then log out.
NestIng JSV Statements
You can also nest for statements. Iike previous looping structures, you must embed a
complete for statement vithin another one. With nested loops, the outer loop starts
one iteration, and the inner loop must complete all ot its iterations betore the outer loop
begins another iteration. Iet`s look at the lorNestA script in ligure 7-18. 1he variable
i is the control variable tor the outer loop and the variable j is the control variable
tor the inner loop.
fIgure 7-18 1he ForNesLA scripL wiLh nesLed for loops and iLs ouLpuL
280 Chapter 7 LoopIng Structures
UnderstandIng the JSV Statement 281
Notice that even though the outer loop begins tirst, the inner loop must complete its
cycle, in this case three iterations, betore the outer loop can begin its second iteration,
at vhich point the inner loop must again complete its cycle ot three iterations betore
the outer loop can begin its tinal iteration.
Next you vill nest three for loops. 1he outermost loop uses variable i, Ioop 2 uses
variable j, and the innermost loop uses variable k.1hese are displayed in the inner-
most loop. Notice that tor each iteration ot i,j changes trom 1 to 2 and k changes
trom 1 to 3 tvice.
1o create a script that uses nested for loops:
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation
vindov.
2. Create a script named ForNested in the $HOME/bin directory.
3. Insert the tolloving lines ot code to create a three-level nested loop. 1he tirst
tvo lines are heading lines.
echo "i j k"
echo "----"
for {{i=1, i <= 3, i++}}
do
for {{j=1, j <= 2, j++}}
do
for {{k=1, k <=3, k++}}
do
echo $i $j $k
done
done
done
4. Save the script, and then quit the editor.
3. Make the script executable, and then execute the script. See ligure 7-19. Atter
the tvo heading lines, the output is 18 rovs ot numbers three columns deep.
6. Close the vindov, and then log out.
7
'HAP1R 7UMMARY
A loop is a set ot statements that are repeated tor some purpose until some
condition changes. Once the condition is reached, the loop terminates. An iter-
ation occurs each time the statements vithin the loop are processed. An intinite
loop occurs it no condition exists to terminate the loop, this consumes an
excessive amount ot processing time and should be avoided. 1he major looping
structures in programming theory are 1hiie, ntii, and Ior.
1he while loop is usetul vhen you don`t knov the number ot iterations.You
can use it to test the condition ot numeric amounts, characters, and commands.
1he syntax ot the shell`s while statement tests the exit status ot the commands
in the 11stA statements. It 11stA returns a zero exit status, then 11stS state-
ments execute. It 11stA returns a nonzero exit status, then 11stS statements
are skipped. Statements tolloving the loop structure are executed regardless ot
the loop`s condition. 1he while statement supports nested loops. Nested loops
allov you to implement loops vithin loops.
Iike the while loop, you use the until statement vhen the number ot itera-
tions is unknovn.You can test the condition ot numeric amounts, characters,
and commands. 1he shell`s until statement tests the exit status ot the com-
mands in 11stA. It 11stA returns an exit status ot one, then the 11stS state-
ments execute. It 11stA returns an exit status ot zero, then the 11stS
statements are skipped. Statements tolloving the loop structure are executed
regardless ot the loop`s condition. 1he until statement supports nested loops.
fIgure 7-19 1he ForNesLed scripL and iLs ouLpuL
SLep 4: ouLpuL o Lhe
ForNesLed scripL-Lwo
headin lines and Lhree
columns o 18 rows
282 Chapter 7 LoopIng Structures
RevIew QuestIons 283
1he shell`s for statement is used vhen the number ot iterations you vant to
pertorm is knovn. 1here are tvo torms ot the for statement. 1he vord list
torm is used to loop through any type ot item in a vord list. 1hese items can
be numbers, characters, or commands. 1he arithmetic expression torm is used
tor incrementing and decrementing numeric values.
6VIW 5US1IONS
1. Lsing the statement, the do statements are executed tor a true
condition.
a. until
b. break
c. continue
d. while
2. A(n, occurs vhen a set ot programming statements are
repeatedly executed.
a. iteration
b. pass
c. true condition
d. loop
3. Lsing the statement, the do statements are executed tor a talse
condition.
a. until
b. break
c. continue
d. while
4. A(n, is the action ot a loop pertorming its statements one time.
a. iteration
b. pass
c. talse condition
d. loop
3. 1he statement is used to terminate a loop.
a. until
b. break
c. continue
d. while
7
6. 1he statement is used to terminate the loop tor one iteration.
a. until
b. break
c. continue
d. while
7. 1he tolloving statement vill execute time(s,.
for{{num=l,num<=5,num++||
do
echo$num
done
a. 0
b. 4
c. 3
d. 6
8. 1he tolloving statement vill execute time(s,.
for {{num=l , num<=5, num++||
done
echo $num
do
a. 0
b. 1
c. 3
d. 6
9. A(n, loop loops torever until terminated.
a. iteration
b. pass
c. intinite
d. continue
10. 1he tolloving statement vill execute time(s,.
for {{num=l , num<5, num++||
do
echo $num
done
a. 0
b. 4
c. 3
d. an intinite number ot
284 Chapter 7 LoopIng Structures
RevIew QuestIons 285
11. What is the result ot the tolloving statements
for animal in cat dog bear
do
echo $animal
done
a. 1he vords cat,dog,animal, and bear are displayed on the screen.
b. 1he vord animal is displayed on the screen.
c. 1he vords cat,dog, and bear are displayed on the screen.
d. Nothing occurs because the statement has a syntax error.
12. 1he tolloving statement vill execute time(s,.
{{t=0||
while $t=l
do
echo "Blue Ocean!"
done
{{t++||
a. 0
b. 1
c. an intinite number ot
d. 2
13. What is the result ot the tolloving statements
{{t=0||
while $t ~lt 3
echo "Taco"
done
a. 1he text 1aco is displayed only once.
b. 1he text 1aco is displayed an intinite number ot times.
c. 1he text 1aco is displayed three times.
d. Nothing occurs because the statement has a syntax error.
14. What is the result ot the tolloving statements
{{g=5||
until $g ~lt l
do
echo $g, {{g~||
done
a. 1he numbers 3, 4, 3, 2, 1 are displayed on the screen on separate lines.
b. 1he numbers 3, 4, 3, 2 are displayed on the screen on separate lines.
c. 1he numbers 4, 3, 2, 1, 0 are displayed on the screen on separate lines.
d. Nothing occurs because the statement has a syntax error.
7
13. 1he tolloving statement displays Popcorn times.
for {{numl=l , numl<=3, numl++||
do
for {{num2=l, num2<=2, num2++||
do
echo "Popcorn"
done
done
a. 0
b. 4
c. 3
d. 6
16. What is the result ot the tolloving statements
{{g=6||
until $g ~ltl
do
echo $g, {{g~||
done
a. 1he numbers 6, 3, 4, 3, 2, 1 are displayed on the screen on separate lines.
b. 1he numbers 3, 4, 3, 2, 1, 0 are displayed on the screen on separate lines.
c. 1he numbers 3, 4, 3, 2, 1, 0 are displayed on the screen on separate lines.
d. Nothing occurs because the statement has a syntax error.
17. What is the result ot the tolloving statements
{{i=l0||, {{=2||
while $ ~lt $i
do
echo $, {{++||
if $ ~gt 5
then break
fi
done
a. 1he numbers 2, 3, 4, 3, 6 are displayed on the screen on separate lines.
b. 1he numbers 2, 3, 4, 3 are displayed on the screen on separate lines.
c. 1he numbers 3, 4, 3, 2 are displayed on the screen on separate lines.
d. 1he numbers 10, 9, 8, 7, 6, 3, 4, 3, 2, 1 are displayed on the screen on sepa-
rate lines.
286 Chapter 7 LoopIng Structures
Hands-on Projects 287
18. Given the tolloving code, vhat value ot the variable named total vill be displayed
{{total=0||
for {{numl=l , numl<=3, numl++||
do
for {{num2=l, num2<=2, num2++||
do
for {{num3=l0, num3>=l, num3~||
do
{{total++||
done
done
done
echo $total
a. 20
b. 30
c. 60
d. 120
19. What is displayed it the tolloving code is executed
for name in 'pwd', do echo $name, done
a. name
b. the present vorking directory
c. a syntax error message
d. nothing
20. What is displayed it the tolloving code is executed
for name in 'echo hi', do echo $name, done
a. hi
b. echo hi
c. a syntax error message
d. nothing
,ANDSON 4ROJC1S
Project 7-1
In this project, you vill create a tile that contains a list ot directories. You vill use the
for loop structure to control the process. Command substitution is needed to read the
contents ot the tile containing the list ot directories. A directory needs to be created tor
each line in the tile.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
,ERHWSR
4VSNIGX
7
2. Create a tile named inlist in the $HOME/bin directory. 1his tile vill contain the
list ot directories, on separate lines, that are to be created.
3. Insert the tolloving lines ot code
Dir1
Dir2
Dir2/Dir2a1
Dir2/Dir2a2
Dir2/Dir2a2/Dir2b1
Dir2/Dir2a2/Dir2b2
4. Create a shell script named Project7-1 in your $HOME/bin directory.
3. Insert the tolloving lines ot code
for dirname in `cat inlist`
do
mkdir $dirname
done
6. Save the script, and then quit the editor.
7. Make the script executable, and then execute the script.
8. Pecord the output.
9. Close your vindov, and then log out.
Project 7-2
In this project, you vill use a looping structure that allovs you to determine it a host
computer is available.You vill use the ping command to accomplish this. It it is avail-
able, you vill telnet to the host computer.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named Project7-2 in the $HOME/bin directory.
3. Insert the tolloving lines ot code
read -p "Enter IP address or host name to ping " PingName
ping -c 2 $PingName
until $? -eg 0 ]]
do
sleep 2
echo "Host not available. Pinging again..."
ping -c 3 $PingName
done
echo "The host is available."
echo "Telnetting to the host."
telnet $PingName
,ERHWSR
4VSNIGX
288 Chapter 7 LoopIng Structures
Hands-on Projects 289
4. Save the script, and then quit the editor.
3. Make the script executable, and then execute the script, and input an existing host
address.
6. Lxecute the script again. 1his time use a host that does not exist.
7. Close your vindov, and then log out.
Project 7-3
In this project, you vill create a script that generates a random number using the
shell`s builtin RANDOM variable. 1he user vill be asked to enter a number betveen 1
and 10, inclusive. 1he loop vill continue until the user guesses the correct ansver.
1he $RANDOM statement vill generate a random number betveen 0 and 32,767,
theretore, a $RANDOM statement vithin the loop vill ensure a random number betveen
1 and 10, inclusive, is generated by the system.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named Project7-3 in the $HOME/bin directory.
3. Insert the tolloving lines ot code
read -p "Guess a number between 1 and 10: " guess
rand=$RANDOM
while true
do
if $rand -ge 1 && $rand -le 10 ]]
then
if $guess -eg $rand ]]
then
echo "Right"
break
else
echo "Try again"
read -p "Guess a number between 1 and: 10 "
guess
rand=$RANDOM
fi
else
rand=$RANDOM
fi
done
4. Save the script, and then quit the editor.
3. Make the script executable, execute the script, and then enter the same number
until you guess the number.
6. Pecord the number ot times it takes you to guess correctly.
7. Close your vindov, and then log out.
,ERHWSR
4VSNIGX
7
Project 7-4
In this project, you vill use the while and until statements as vell as nested loops.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named Project7-4 in the $HOME/bin directory.
3. Insert the tolloving lines ot code
let "x=1" # Same as {{x=1}}
while $x -le 5 ]] # Outer loop begins
do
let "y=4"
until $y -le 1 ]] # Inner loop begins
do
let y-- # Same as {{y--}}
echo $x $y
let c++ # Same as {{c++}}
done # Inner loop ends
let x++ # Same as {{x++}}
done # Outer loop ends
echo "The number of times looped is: " $c
4. Save the script, and then quit the editor.
3. Make the script executable, and then execute the script.
6. Close your vindov, and then log out.
Project 7-5
In this project, you vill create a script that displays Happy Birthday' it the current
month and day happen to match the system date.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named Project7-S in the $HOME/bin directory.
3. Insert the tolloving lines ot code
read -p "Enter your three-letter birth month
{e.g., Feb} ?" BirthMonth
read -p "Enter your two-digit birth day
{e.g., 07} ?" BirthDay
month=`date [ cut +%b`
day=`date [ cut +%d`
if $BirthMonth -eg $month && $BirthDay -eg $day ]]
then
HappyBirthday="Y"
else
HappyBirthday="N"
fi
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
290 Chapter 7 LoopIng Structures
Hands-on Projects 291
while $HappyBirthday = "Y" ]]
do
echo "Happy Birthday!"
sleep 10
done
4. Save the script, and then quit the editor.
3. Make the script executable, execute the script, and then input your birth month
and birthday.
6. Pecord the result.
7. Lxecute the script again. 1his time input the current day and month.
8. Pecord the result.
9. Hov vould you terminate the script
10. Close the vindov, and then log out.
Project 7-6
In this project, you vill revrite the Happy Birthday' script using the case statement
tor the decision and the until statement tor the looping structure.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Copy Project7-S to Project7- in your $HOME/bin directory. (It you did not
complete Project 7-3, the code tor this script is included in Step 3 ot that project.,
3. Write the pseudocode or drav a tlovchart tor using the case statement tor the
decision and the until statement tor the loop.
4. Modity Project7- to use the case statement and the until statement.
3. Pecord the script.
6. Save the script, quit the editor, make the script executable, execute the script, and
input your birth month and birthday vhen prompted.
7. Pecord the result.
8. Lxecute the script again. 1his time input the current day and month.
9. Pecord the result.
10. Close your vindov, and then log out.
Project 7-7
In this project, you vill create a script that allovs the user to enter a passvord. 1he pass-
vord the user enters vill be suppressed vith the ~s option ot the read statement. It the
user tails to input the correct passvord atter three tries, then a message vill be displayed
indicating that the number ot attempts has been exceeded, and the script vill terminate.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named Project7-7 in the $HOME/bin directory.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
7
3. Insert the tolloving lines ot code
pw=""
password="cactus207"# This is the password to compare.
{{count=1}}
while $pw != $password ]]
do
{{count++}}
read -s -p "Enter password: " pw
echo ""
if $pw = $password ]] # Is there a match?
then
echo "Correct!"
break
fi
if $count -gt 3 ]] # Limit the number of times to 3.
then
echo "Too many attempts!"
break
fi
done
4. Save the script, quit the editor, and then make the script executable.
3. Lxecute the script several times using the correct passvord (cactus207, and incor-
rect passvords.
6. Close your vindovs, and then log out.
Project 7-8
In this project, you vill create a menu script alloving a user to enter options to run
Iinux commands.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script, named Project7-8 in the $HOME/bin directory.
3. Insert the tolloving lines ot code
YN="Y"
while $YN = "Y" ]]
do
clear
echo " MAIN MENU"
echo " 1. Long Listing"
echo " 2. Current Users"
echo " 3. Process Listing"
read -p "Enter a valid selection 1-3]" selection
case $selection in
,ERHWSR
4VSNIGX
292 Chapter 7 LoopIng Structures
Case Projects 293
1} ls -l [ more ,,
2} who [ more,,
3} ps [ more,,
*} echo "Enter a valid selection 1-3]" ,,
esac
read -p "Continue {Y/N} ?" YesNo
YN=`echo $YesNo [ tr :lower:] :upper:]`
done
4. Save the script, quit the editor, and then make the script executable.
3. Lxecute the script, inputting the numbers 1, 2, and 3 tor the menu options.
6. Pecord your observations.
7. Close your vindovs, and then log out.
'AS 4ROJC1S
Case 7-1
1MI is requesting your services again.You are to create a menu script that allovs the user
to enter all ot the options given in Case 1 in Chapter 6. Be sure to create a tlovchart or
pseudocode betore implementing your script. Make sure you run and test your script.
Case 7-2
You are to create a menu ot Iinux commands that a user can run.You vill need to copy
the Project7-8 script and modity it. 1here vill be a tourth menu option that brings up
another menu, called the Pemote System Menu. Lsers must enter a passvord to gain
access to this menu.1he passvord should not be displayed on the screen. It an incorrect
passvord is entered, an appropriate message is displayed indicating an invalid passvord
and the user is returned to the MAIN MLNL. It the user enters a correct passvord,
then tvo options are displayed. 1he tirst option allovs the user to ping to another
system.You need to allov tor the user to input either an IP address or hostname to ping.
lor the second option, allov the user to telnet to another system. Provide tor the user
to input either an IP address or hostname tor use vith telnet. You vill use a looping
structure vithin the Pemote System Menu to allov the user to ping or telnet until he
or she decides not to continue.
'EWI
4VSNIGX
'EWI
4VSNIGX
7
295
',%48)6

*92'8-327 %2( %66%=7


-RXLMWGLETXIV]SY[MPP
9RHIVWXERHJYRGXMSRW
9RHIVWXERHJYRGXMSRTEVXW
-QTPIQIRXJYRGXMSRW
-QTPIQIRXEJYRGXMSRPMFVEV]
9RHIVWXERHEVVE]W
(IGPEVIEVVE]WERHEWWMKREVVE]ZEPYIW
%GGIWWERHGPIEVZEPYIWMREREVVE]
'VIEXIVIGSVHWYWMRKEVVE]W
-
n thMs chapter, you vMll learn hov to Mmplement tunctMons and arrays
lunctMons are small mMnMscrMpts that aMd Mn the development ot programs
because theMr code can be used numerous tMmes and achMeve consMstent
results lunctMons also tacMlMtate the use ot a tunctMon lMbrarya collectMon ot
tunctMons that multMple users can utMlMze Arrays allov you to assMgn multMple
values to a sMngle varMable name 1hMs Ms usetul because Mt allovs you to ret-
erence all the elements ot the array usMng a sMngle varMable nameYou can also
use loopMng structures to easMly manMpulate the data vMthMn an array
9ND)6S8ANDIN+ *UNC8IONS
A functMon is a set ot statements that can be used to pertorm a specitic task. lunctions
are selt-contained blocks, or chunks, ot code that can be used multiple times simply
by reterencing the tunction name.
FuncLions can accepL values and reLurn a resulL. FuncLions are called subpro-
rams, subrouLines, or modules in oLher prorammin lanuaes.
lunctions are similar to scripts in that both contain shell statements. Hovever, tunctions
execute vithin the current shell and scripts are spavned as subshells in a child process.
Because a script creates a nev process, the operating system has more to manage in the
process tree, vhich translates to the additional use ot processor time and memory.
lunctions, on the other hand, do not require additional processor time or memory. A
tev other benetits ot using tunctions include reusability, reduction ot redundancy, and
modularization.
*uRcXMoR 6eusabMlMXy
lunctions are reusable. Because ot this, you do not need to recreate them to complete
the same tasks over and over. Lsing the same tunctions multiple times saves you time
and helps to errorproot tuture programs that use the original, proven tunctions. lor
example, say you are a shell programmer tor a large international bank, 1he Big Bank.
1hey vant you to vrite a program, vhich converts currency trom L.S. dollars to
Lurodollars and vice versa, and that can be used by several ditterent users and scripts
throughout the day. One vay to complete this task is to create a tunction. A user could
give the tunction a value ot either L.S. dollars or Lurodollars to convert, and the tunc-
tion vould return the converted value. At a large international bank, many users could
implement this tunction over the course ot the business day. 1he same conversion pro-
gram could be vritten using a script, hovever, you vould have the added overhead vith
the associated child processes. lunctions are executed by simply entering their names,
or they can be accessed vithin a shell script.You reuse the code in a tunction by reter-
ring to it as many times as you need it in a script.
*uRcXMoRs 6eHuce 6eHuRHaRcy
1he use ot tunctions also reduces the redundancy in a programming environment. In
many large programming shops there may be multiple programmers vorking on the
same problem separately and vithout knovledge ot the other people`s vork. At best,
although the programmers may solve the problem correctly, they duplicated ettort. At
vorst, the programmers may end up vith ditterent solutions to the same problem, vhere
one or both are incorrect. One or more programmers vorking on a single problem and
implementing common tunctions can reduce this redundancy.
8MT
296 CLaTXeV 8 *uRcXMoRs aRH AVVays
URHeVsXaRHMRK *uRcXMoRs 297
1ake a typical programming task that could be vorked on by several programmers that
is conducive to the use ot a tunction. lor example, the programming statt at 1he Big
Bank needs to convert dates to and trom ditterent tormats. Some date tormats are
MMDDYYYY, vhile others use the numeric ulian date ot YYYYDDD, and still
others employ one ot the Luropean tormats, typically DD-MMM-YYYY. One or more
tunctions could be created to convert one date tormat to another. Once the data con-
version tunction is complete, all programmers and users can implement the tunction
vhen needed vithout having to recreate the conversion code.
Iet`s look at an overviev ot hov tunctions can be created and used vithin a script.
ligure 8-1 shovs a portion ot a script that contains tvo tunctions and calls the tunc-
tions several times. Note this script does not vork as is, but is intended to help you
understand the placement and usage ot tunctions vithin a script. In ligure 8-1, a pro-
grammer vith 1he Big Bank has created tvo tunctions, DateConversion and
CurrencyConversion, detined and called vithin the Accounting script. Although not
coded in the tigure, these tunctions have their ovn commands that accomplish their
intended goals. lor example, the DateConversion tunction converts one date tormat to
another. 1he CurrencyConversion tunction converts one currency rate to another. As
vith actual scripts, the main portion ot the script, vhich talls under the comment 1he
Accounting Script in the tigure, is located belov the detinition ot the tunctions. Once
a tunction is created, it can be used any number ot times in the script simply by reter-
encing its name tolloved by any necessary parameters. Notice that
CurrencyConversion $Amount is listed tvice in ligure 8-1, this means that this
tunction is called tvo times in the script.
Keep in mind that the programmers vriting the scripts are responsible tor vriting the
tunctions. 1hey must understand vhat each tunction does so they knov vhen to reter-
ence it by name and vhat, it any, parameters are needed tor processing. It the program-
mers vanted the DateConversion tunction to process data again, they vould have to
place another reterence to it in the script. lor the CurrencyConversion tunction, the
parameter, $Amount, is the data that the tunction processes. lor the DateConversion
tunction, the parameter $DateToConvert is processed. lor nov, just understand that
this is an overviev ot the placement and usage ot tunctions vithin scripts. 1he actual
creation and implementation vill be discussed later in this chapter.
MoHulaVMzaXMoR
ModularMzatMon is the process ot breaking a program into manageable parts, called
nodulIs. lunctions are otten called modules. In ligure 8-1, you see tvo detined mod-
ulesthe tvo tunctions and one main program calling them. Because tunctions allov
you to break your program into smaller components, you can isolate a problem to a spe-
citic area in the program. In ligure 8-1, it there vere a problem vith the currency
amount not converting correctly, you could isolate the problem related to that tunction
instead ot having to reexamine the code in the date conversion tunction or somevhere
else in the script.
8
9ND)6S8ANDIN+ *UNC8ION 4A68S
lunctions are implemented vithin a shell script and are usually placed at the beginning
ot the script. Here is the general tormat ot a tunction
function funct1on~name { |
{
11st
}
1he name ot the tunction is required, and you as the programmer need to decide vhat
to name it.You need to include either the keyvord function at the beginning ot the
tunction or use a pair ot ending parentheses {| atter the tunction name. Hovever, it you
choose to, you can use both. 1he use ot the keyvord function or the parentheses are
vhat detine the tunction in the script. 1he lett { and right } braces are required and
indicate the tunction`s beginning and end and act as the tunction`s boundaries. 1he lett
brace can be placed on the same line as the tunction declaration as in function
funct1on~name {| {. 1he right brace can be placed on the last line as long as it is
preceded by a semicolon.You can also place the right brace on its ovn separate line. It
is important to understand the concept ot boundaries because it you place a command
insioe the tunction that should have been placed outsioe the tunction, you most likely vill
encounter logic errors or syntax errors.1he commands in the 11st are any valid Iinux
commands.
*MKuVe 8-1 9se o uncLMons Mn shell scrMpLs
CurrencyConversion
uncLion
FuncLion calls rom
Lhe main parL o Lhe
AccounLin ScripL
DaLeConversion
uncLion
298 CLaTXeV 8 *uRcXMoRs aRH AVVays
ImTlemeRXMRK *uRcXMoRs 299
You can also place Lhe uncLion on a sinle line usin eiLher o Lhe ollowin
meLhods: functionfunct1on~name {11st,} or funct1on~
name {|{ 11st, }. NoLe LhaL Lhe semicolon is required aLer 11st
when you creaLe a uncLion on a sinle line.
Consider the tolloving example. 1he tunction named DisplayHello has only one state-
ment, echo "hello". When the tunction is reterenced or called, it simply displays the
text hello on the screen.
function DisplayHello { | {
echo "hello"
}
In a script, you make use ot the commands in a tunction by mentioning, or reterencing,
the tunction by name, in this case DisplayHello. 1his is knovn as a functMon call.
1hink ot it as calling upon the tunction to do its vork.
When you put the tunction and the tunction call together, you get the tolloving com-
pleted script that displays hello on the screen and can be added to an existing script
or program
function DisplayHello { | {
echo "hello"
}
DisplayHello
-M4L)M)N8IN+ *UNC8IONS
As you knov, tunctions are generally located at the beginning ot the script, and their
statements are only executed it the tunction is called. 1his is because the shell needs to
be avare ot the tunction betore the shell calls it. In other vords, you need to detine and
create your tunction betore you utilize it.You can place commands betore the tunction
as long as they don`t reterence the tunction. When the shell interprets a script, it reads
past the tunction and executes statements atter it. Once the tunction is called, the shell
executes the statements vithin the tunction. Atter the tunction has completed, the shell
returns control to the statements tolloving the tunction call.
You need to understand placement ot the tunction in shell scripts because improper
placement can cause your script to result in an error. ligure 8-2 shovs the shell`s response
to the DisplayIt script that contains a tunction that is detined atter the tunction call.
When the DisplayIt script executes, the shell cannot tind the tunction and results in a
command not tound error.
In ligure 8-3, the DisplayIt script has been moditied to place the tunction call atter the
tunction. When the script executes, the shell can locate the tunction. You can see that
the script displays the text it on the screen.
8MT
8
*uRcXMoRs CallMRK *uRcXMoRs
You can use the code ot an existing tunction vithin another tunction. 1his allovs you
to use an existing tunction that is already presentthere is no need to revrite the code.
Iook at an example dealing vith pay tor regular time versus pay tor overtime. As you
*MKuVe 8-3 ResulLs o correcLly placed uncLMon
*MKuVe 8-2 Lrror resulLMnK rom an Mmproperly placed uncLMon
300 CLaTXeV 8 *uRcXMoRs aRH AVVays
ImTlemeRXMRK *uRcXMoRs 301
knov, it a vorker`s hours are less than or equal to 40, then the pay tor regular time is cal-
culated as hours multiplied by rate ot pay. It the hours vorked exceed 40, then the over-
time pay is comprised ot tvo parts, the amount ot overtime pay plus the amount ot pay tor
regular time. lor the overtime pay, the calculation is the number ot hours over 40 multi-
plied by one and a halt (1.3, and then multiplied by the rate ot pay. 1o this, you add the
regular time calculation.You must code tor the possibility ot both regular and overtime cal-
culation. So, tor the regular time calculation, you can create a tunction called Pegular1ime.
lor the overtime calculation, you can create a tunction called Over1ime. It needs to include
a calculation tor the tirst component, vhich is the actual overtime pay calculation. lor the
second component ot the overtime calculation, you can simply call the Pegular1ime tunc-
tion. ligure 8-4 shovs a partial script that implements this example. Note the script can-
not run as is. It is simply used to shov you hov tunctions vithin tunctions can be used.
In terms ot hov to set up a tunction call vithin another tunction, the general tormat is
functionA {|
{
commands
functionB # Call to other function
}
functionB {| # Called from functionA
{
commands
}
# Main section
functionA
*MKuVe 8- A uncLMon callMnK anoLher uncLMon
8
Iook at a simple example. ligure 8-3 shovs the contents ot a script named
lunctionIink. 1he main section ot the script calls the tunction named Apple and passes
program control to it. 1he tirst statement vithin the Apple tunction displays the text
Apple, and then calls the tunction named Grapes and control passes to the Grapes tunc-
tion. 1he Grapes tunction displays the text Grapes on the screen. When the Grapes
tunction completes, control returns to the Apple tunction. Because there are no other
statements vithin the Apple tunction, control returns to the statement tolloving the
original tunction call to Apple in the main section ot the script.
AvoMHMRK SyRXax )VVoVs
1here are lots ot syntax errors you can avoid just by paying caretul attention vhen you
type your scripts. Hovever, here are a couple ot the more common syntax errors that
can occur vhen you are creating tunctions. As you knov, vhen creating a tunction, you
must use either the keyvord function prior to the name ot the tunction or use the
parentheses, { | atter the name ot the tunction. Hovever, it both are lett ott, the shell
generates an error message. 1his is a common mistake that is easily avoided by making
sure you are using the correct tormat vhen creating tunctions. So, funct1on~name { |,
function funct1on~name, or function funct1on~name { | are acceptable.
Another potential problem common among programmers vho are tamiliar vith ava and
other languages that make greater use ot parentheses, is adding the parentheses { |, atter
the tunction name vhen calling the tunction. lor example, it you create a tunction
*MKuVe 8-5 FuncLMonLMnk scrMpL where one uncLMon calls anoLher
302 CLaTXeV 8 *uRcXMoRs aRH AVVays
ImTlemeRXMRK *uRcXMoRs 303
named WhoIist, then you call it in a script by simply using WhoList, not WhoList {|.
It you add parenthesis, the shell generates an error.
Next you vill create a simple tunction to get started.
1o crIatI a scrMpt that usIs a functMon to dMspla] thI tIt hovd] on thI scrIIn
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named FunHovd] in your $HOME/bin directory.
3. Insert the tolloving lines ot code to create and call the tunction
function howdy { }
{
echo "howdy"
}
howdy
4. Save the script, and then close the editor.
3. Make the script executable, and then run the script. Notice that hovdy
appears on your screen. ligure 8-6 shovs the complete script and its execution.
6. Close the vindov, and then log out.
*MKuVe 8-6 A scrMpL usMnK a sMmple uncLMon named howdy
ResulLs o runnin Lhe
FunHowdy scripL
8
You can create a tunction that the shell can use vithout creating a script.1o do this vith
the code used in the lunHovdy script, you enter the code at the command line. 1he
shell prompts you vith an arrov atter each line ot text. 1he right arrov symbol is used
by the shell to indicate it is avaiting more commands.You can call the tunction directly
vithin the shell by typing its name at the command line, in this case, howdy.When cre-
ating a tunction directly vithin the shell, it is not saved permanently as it is vith a tile.
1he shell temporarily saves the tunction in memory.When you log out, the tunction no
longer exists.
ligure 8-7 shovs the creation ot the hovdy tunction and the results ot the tunction call
pertormed at the command line. Notice that ligures 8-6 and 8-7 are similar. Hovever
in ligure 8-7, you can tell that the tunction is not a part ot a script, but is detined at the
command line as indicated by the arrov symbols.
4assMRK Values Xo *uRcXMoRs
You can make your tunctions more tlexible by alloving the script to give the tunction
ditterent values. When you give a value to a tunction, it is termed passMng.1he value
ot the variable is passed to the tunction. Once the tunction has the value, the tunction
can pertorm calculations or comparisons on the value. Passing values to tunctions is sim-
ilar to passing values to shell scripts on the command line. 1hey are both positional. 1o
pass values to a tunction, you place the values, separated by spaces, immediately atter the
tunction name. 1he general tormat ot passing a value to a tunction is
Funct1on~name va1ue1 va1ue2 .va1ueu
*MKuVe 8-7 CreaLMnK a uncLMon dMrecLly Mn Lhe shell
30 CLaTXeV 8 *uRcXMoRs aRH AVVays
ImTlemeRXMRK *uRcXMoRs 305
lor example, say you are calculating payroll in a script tor Ia 1asha 1revor`s 1ravel Agency,
Inc.You could pass a positional parameter to the CalculatePay tunction as tollovs
CalculatePay $l $2 $3
Or you could pass the contents ot variables such as Lmployee, Pate, and Hours as
demonstrated in the tolloving code
# In the function call, the first value is $Employee, the
second is $Rate, and the third is # $Hours.
CalculatePay $Employee $Rate $Hours
Next you vill vrite a script that passes values using positional parameters to a tunction.
1he script vill accept tvo positional parameters, $l and $2. 1he tunction call vill also
use an if statement vith the elif clause to determine it the tirst number is equal to,
less than, or greater than the second number. By alloving you to pass any tvo values to
the script and having the tunction compare them, this exercise demonstrates the tlexi-
bility ot using a tunction.
1o crIatI a scrMpt that passIs posMtMonal paranItIr valuIs to a functMon
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named ConparI1vo in the $HOME/bin directory.
3. Insert the tolloving lines to create a tunction called compare that compares the
values ot the positional parameters that are passed to it using an if statement
compare {}
{
if $1 -eg $2 ]]
then
echo $1 "eguals" $2
elif $1 -gt $2 ]]
then
echo $1 "is greater than " $2
else
echo $1 "is less than " $2
fi
}
4. Insert the tolloving lines ot code to create the comment line and then call
the tunction
# The compare function call:
compare $1 $2
3. Save the script, and then close the editor.
8
6. Make the script executable, and then to execute the script type
CompareTwo44. A message is displayed indicating the tvo parameters
are equal.
7. Lxecute the script again. 1his time, type CompareTwo4 6. A message is
displayed indicating that 4 is less than 6.
8. Lxecute the script one last time. 1his time, type CompareTwo42. A mes-
sage is displayed indicating that 4 is greater than 2.
9. Close your vindov, and then log out.
Next you vill create a script that uses variable names in a tunction. Note that only the
content, or the data, is passed to the tunction, not the name ot the variable itselt. You
vill use the read command to accept the values trom the keyboard. 1he values vill
then be passed to the tunction and multiplied. 1he goal ot this exercise is to help you
understand hov to read data and pass it to a tunction tor processing.
1o crIatI a scrMpt that passIs thI varMablI valuIs to a functMon
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named ProductPrMcICalculatMon in the $HOME/bin
directory.
3. Insert the tolloving lines ot code to create the tunction named Multiply. 1he
tunction accepts tvo parameters and calculates their product. 1he product is
stored in the variable named Mult.
function Multiply
{
{{Mult = $1 * $2}}
}
4. Insert the tolloving lines ot code to read the price and quantity trom the
keyboard
read -p "Enter Product Price: " Price
read -p "Enter Product Quantity: " Quantity
3. Insert the tolloving statement to call the tunction named Multiply vith the
variables Price and Quantity
Multiply $Price $Quantity
6. Insert the tolloving statement to display the variable named Mult
echo "The total is $Mult"
7. Save the script, and then close the editor.
306 CLaTXeV 8 *uRcXMoRs aRH AVVays
ImTlemeRXMRK *uRcXMoRs 307
8. Make the script executable, execute the script, and vhen prompted, input 10
tor the Price and 100 tor the Quantity. 1he product ot 1000 is displayed on
the screen.
9. Close your vindov, and then log out.
*uRcXMoR ScoTe
Variables have a scope associated vith them.1he scopI ot a variable is the set ot bound-
aries that establishes trom vhere the variable`s contents can be accessed. 1here are tvo
attributes ot variables scopes
global
local
A variable is considered to have global scopI it it can be accessed anyvhere vithin the
script. All tunctions have access to global variables and can change the value ot the global
variable.
A variable is considered to have local scopI it it is detined vithin a tunction.1he local vari-
able can only be accessed and changed by the tunction vhere it is detined.You cannot change
a local variable in a tunction vhere it is not detined. lor example, you cannot change a local
variable outside the tunction in the main part ot the script.You use the local statement to
declare a local variable.
lor instance, you create and set a local variable vith the statement local "PayDay=Y"
in a tunction named Payroll.You can only read and set PayDay vithin Payroll.You can-
not read or set this variable anyvhere else. Nov, vhat it you have another tunction that
uses the same variable name, PayDay. Although this is not recommended, it does occur
in the programming industry. It you do have another tunction, named Paycheck, that has
a local variable vith the same name, PayDay, the shell treats each as local to the tunc-
tion vhere they are detined.1hink ot the variable names as being Payroll`s PayDay vari-
able and Paycheck`s PayDay variable. 1hey have the same name, PayDay, but are actually
unique because they are in separate tunctions. It is like having tvo people vith the same
last name, but ditterent tirst names. What makes them unique is their tirst name. 1o the
shell, a global variable and a local variable vith the same name are treated as ditterent
variables because ot vhere they are created.
You can only use Lhe local sLaLemenL wiLhin a uncLion. l you use iL ouL-
side a uncLion, you receive an error rom Lhe shell indicaLin LhaL iL can only
be used in a uncLion.
Consider this example. In the lunScope script shovn in ligure 8-8, you see that the
variable x is detined and set local to the tunction using the local "x=5" statement.
Also, x is set globally vith {{x=l0||. So, to vhat is x really set 1his is vhere the
importance ot scope takes ettect. It you access the locally set x vithin the tunction,
8MT
8
then you are accessing the value 3. It you access the globally set x anyvhere vithin
the script, then you are accessing the value 10. ligure 8-9 shovs the output ot the
lunScope script, vhich reintorces the concept ot variable scope. By locally detining a
variable, you don`t have to be concerned vith overriding its contents outside ot the
tunction.
AlLhouh duplicaLe variable names can be deined wiLhin dierenL uncLions,
Lheir use is noL recommended due Lo Lhe conusion LhaL arises.
You can detine a global variable anyvhere in the script, including vithin a tunction. As
long as you don`t precede the variable name vith the local keyvord, the variable is
considered global and it can be changed in any tunction or in the main portion ot the
script. Next you vill create a script, similar to the lunScope script, vhich vill include
tvo tunctions, tunction1 and tunction2. 1he variable x vill not be detined using the
local keyvordhence it vill be a global variable and able to be changed anyvhere.
*MKuVe 8-8 1he FunScope scrMpL LhaL seLs Lhe varMable qxr boLh Klobally and locally
8MT
308 CLaTXeV 8 *uRcXMoRs aRH AVVays
ImTlemeRXMRK *uRcXMoRs 309
1o crIatI a scrMpt that dInonstratIs thI usI of sIttMng and dMspla]Mng a global
varMablI
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named FunScopIA in the $HOME/bin directory.
3. Insert the tolloving lines ot code to create tunction1. Notice that the variable
x is set to 3 in this tunction.
function function1
{
{{x=5}}
echo "Within function1:" $x
}
4. Insert the tolloving lines ot code to create tunction2. Notice that the variable
x is set to 6 in this tunction.
function function2
{
{{x=6}}
echo "Within function2:" $x
}
*MKuVe 8-9 ResulLs o FunScope scrMpL
8
3. Insert the tolloving lines ot code to set x to 10, display x, and call the
other tunctions.
{{x = 10}}
echo "Outside function1:" $x
function1
echo "Outside function1:" $x
function2
echo "Outside function2:" $x
6. Save the script, and then close the editor.
7. Make the script executable, and then execute the script. 1he value ot x is
displayed on the screen. Because x is a global variable, the contents ot x
can be set anyvhere. Peter to ligure 8-10 tor the output. Compare this to
ligure 8-9. In ligure 8-9, the global variable x is not changed in tunction1,
and the original value 3 remains.
8. Close your vindov, and then log out.
*MKuVe 8-10 1he FunScopeA scrMpL seLLMnK Lhe Klobal varMable qxr
310 CLaTXeV 8 *uRcXMoRs aRH AVVays
ImTlemeRXMRK *uRcXMoRs 311
URHeVsXaRHMRK XLe 6eXuVR SXaXus of a *uRcXMoR
It you vant to test vhether a tunction resulted in an error, you can have the tunction
return an exit status using the return keyvord.1he return statement returns the exit
status ot a tunction to the shell, much like an exit status is returned tor success or tail-
ure ot a script or command. 1he general tormat ot the return statement is as tollovs
return n
1his is vhere n is the return status you specity.You can then test tor the return status in
an if statement. It the tunction completes successtully, then the tunction returns vith
a completion status ot zero (true,. It the tunction does not complete successtully, then
the tunction returns a completion status ot one (talse,. Note that the coding ot the tunc-
tion and vhether or not the return status is zero tor a true condition and one is tor a
talse condition is up to the programmer. Hovever, the standard is to use a return value
ot zero tor true (success, and a return value ot one tor talse (tailure,.You need to plan
ahead vhen vriting scripts. It you reverse the order ot the return statements vithin
the tunction, any statement may end up executing statements you did not intend tor it
to execute.
In the tolloving example, a script includes a tunction that is used to determine it a direc-
tory exists. 1he name ot the directory is passed to the script on the command line, and
the script calls the tunction using the positional parameter, $l. It the directory exists,
then the script changes to the directory, displays the current directory, and displays a list-
ing ot the directory`s contents. It the directory does not exist, an appropriate message is
displayed indicating the directory does not exist. 1he tunction returns a status ot zero
tor success and a status ot one tor tailure. 1hen, the script tests the value ot the return
status using an if.then.else statement. ligure 8-11 shovs the contents ot the
DirLxistsA script and the DirLxists tunction. Notice the use ot the list command vith
the statement {cd $l, pwd, ls ] more|. Although you are not required to use a
{list| command here, it is done here so you can see variations in the vay you can
vrite commands.
Reer Lo ChapLer 3 or compleLe coverae o Lhe lisL commands.
8MT
8
In ligure 8-12, the DirLxistsA script is executed tvice. Once vith tmp as a positional
parameter and the second time vith a directory that does not exist. Notice the ditter-
ences in messages.
*MKuVe 8-12 ResulLs o Lhe DMrLxMsLsA scrMpL run LwMce
*MKuVe 8-11 1he DMrLxMsLsA scrMpL MncludMnK Lhe DMrLxMsLs uncLMon
312 CLaTXeV 8 *uRcXMoRs aRH AVVays
ImTlemeRXMRK *uRcXMoRs 313
Next you vill use a tunction to determine it a tile exists. It the tile exists, the script
removes it and displays a message indicating that it has been removed. 1he tilename is
passed to the script and tunction as a positional parameter. 1he tunction returns a status
ot zero tor success or one tor tailure. 1hen the script tests the value ot the return status
ot the tunction using an if.then.else statement.
1o crIatI a scrMpt that tIsts thI rIturn status of a functMon
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named 1IstRIturn in the $HOME/bin directory.
3. Insert the tolloving lines ot code to create the tunction named lileLxist. It
accepts a positional parameter and tests tor its existence.
function FileExist{}
{
if -a $1 ]]
then
return 0
else
return 1
fi
}
4. Insert the tolloving lines ot code to test the tunction. Note the if
FileExist$l statement has the attect ot calling the tunction and testing
its return status. It zero is returned, the ifFileExist$l condition is true
and the tile is removed. It the tile does not exist, the return status ot the
tunction is one and the else clause causes a message to be displayed indicat-
ing the tile is not present. 1hus, the tile von`t be removed.
if FileExist $1
then
rm $1
echo $1 "File removed!"
else
echo $1 "File is not present"
fi
3. Save the script, close the editor, and then make the script executable.
6. Create a tile named fMlI4tt so you can see vhat happens vhen you run the
script vith a tile that does exist.
7. 1ype TestReturnfile4.txt, and then press LntIr. 1he tile named
tile4.txt is removed. See ligure 8-13. A message appears indicating the tile has
been removed.
8
8. 1ype TestReturnfile4000.txt, and then press LntIr. See ligure 8-13.
A message appears indicating the tile is not present.
9. Close your vindov, and then log out.
)xToVXMRK *uRcXMoRs
You can export a tunction to shells created by the current shell. You vould do this to
use the tunctions in any subshell spavned trom the current shell.1o do this, you use the
export statement vith the ~f option. 1he export statement allovs tunctions and
variables to be used by subshells.1he ~f option is required vhen exporting a tunction.
It you omit it, your tunction is not exported.1o export the tunction, you run this command
export -f funct1on~name
1his is vhere funct1on~name is the name ot a tunction that already exists.
In ligure 8-14, the tirst statement creates a tunction named hi at the command line.
Next, a subshell ot bash is spavned using the bash statement. 1hen comes the test.1he
third statement in ligure 8-14 calls the hi tunction. Hovever, because you are in a sub-
shell and the tunction has not been exported, the tunction call to hi tails, the tunction
does not exist in the subshell. In the next sequence ot statements, the subshell is exited,
the tunction is exported, another subshell is created, this time, the tunction call to hi
succeeds.
*MKuVe 8-13 RunnMnK Lhe 1esLReLurn scrMpL LwMce
SLep 7: messae indicaLin
ile has been removed
SLep 8: resulLs show
ile is noL presenL
31 CLaTXeV 8 *uRcXMoRs aRH AVVays
ImTlemeRXMRK a *uRcXMoR LMbVaVy 315
-M4L)M)N8IN+ A *UNC8ION 0I&6A6Y
1he shell allovs you to create a functMon lMbrar], vhich is a tile that contains the tunc-
tions you vant to make available to scripts tor yourselt and others.1he benetit ot a tunc-
tion library is that you create the tunction in the library only once. Any moditications
to the tunction attect all the scripts that use it. Also, it there is a problem vith a tunc-
tion, you only have to make corrections in one placethe library tile. Generally, you
place tunctions that are trequently used in the tunction library. 1his enhances the pro-
gramming ettort involved tor all.
Here are the recommended steps that allov you to create and implement a tunction library
1. Create a tile containing your tunctions.
2. Place the tile in the $HOME/bin directory. It you have access to user pass-
vords, you can place the tile tor all users in usrlocalbin.
3. Lse the source command in a script. 1he source command reads and exe-
cutes a script vhen you enter sourcescr1t~name. It the script contains
a tunction detinition, you can then call the tunction in the script. Note that
you must run the source command prior to calling a tunction it contains.
1here are numerous uses tor a tunction library. lor instance, say you vork as a System
Administrator and script programmer tor Giant 1op Circus Pertormers, Inc. You inter-
viev the users, and it has been determined that certain processes need to be automated
*MKuVe 8-1 LxecuLMon o a uncLMon Mn a subshell wMLh and wMLhouL exporLMnK Lhe uncLMon
rom Lhe parenL shell
FuncLion creaLed aL Lhe
command line
Spawns a subshell
8
due to their trequent use.You decide the best vay to do this is to create the tolloving
tunctions
A tunction named goto vhich includes these commands cd, ls, and pwd.
A tunction named WhoProc vhich includes these commands who and ps.
A tunction named Prompt, vhich changes the prompt to include the date
and the tull path ot the present vorking directory.
Next you vill create a tunction library containing the tunctions tor Giant 1op Circus.
You vill also use these tunctions vith the source command.
1o crIatI a functMon lMbrar] fMlI and usI Mts functMons
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a tile named FunLMbA in your $HOME/bin directory.
3. Insert the tolloving lines ot code to create the three tunctions to be used by
the shell
function goto {}
{
cd $1
ls $1
pwd
}
function WhoProc {}
{
who
ps
}
function Prompt {}
{
PS1='`date` `pwd` ->' # PS1 is the variable for the
prompt.
}
4. 1o utilize the tunctions in the tunction library named lunIibA, type source
FunLibA, and then press LntIr.
3. 1o shov that the tunctions are created, type typeset-f[more, and then
press LntIr.You vant to use the typeset~f command, because the ~f
option is used to display only tunctions. It you leave the ~f option ott, the
typeset command displays variables that are set, too. See the tunctions dis-
played in ligure 8-13.
Recall LhaL Lhe seL and declare commands display all variables, includin
uncLions, Loo.
8MT
316 CLaTXeV 8 *uRcXMoRs aRH AVVays
URHeVsXaRHMRK AVVays 317
6. 1o use the WhoProc tunction, type WhoProc, and then press LntIr. See
ligure 8-13. A list ot users and processes is displayed.
7. 1o use the Prompt tunction, type Prompt. See ligure 8-13.Your
prompt changes.
8. Close your vindov, and then log out.
URseXXMRK a *uRcXMoR
You can remove a tunction trom use vith the unset command.You do this it you no
longer need the tunction. lor example, unset WhoProc removes WhoProc trom mem-
ory and no longer allovs you to use the tunction. Hovever, this does not remove it trom
the lunIibA script. It you vanted to remove the tunction trom the tunction library, you
edit the tunction library tile and delete the lines associated vith the tunction.
9ND)6S8ANDIN+ %66AYS
An arra] is a variable that contains a series or list ot elements. An array reters to the ele-
ments in its list using an integer starting trom zero, this number is called a subscrMpt or
an MndI. 1he subscript begins at zero and there is no maximum number limiting the
size ot the array.When the array is created, the subscripts are created automatically, they
cannot be changed or deleted.You use an array vhen you have a group ot variables that
contain data values that are similar in nature. Instead ot creating a variable tor each value,
you create a single variable name and then place all ot the values in this array variable.
*MKuVe 8-15 9LMlMzMnK uncLMons Mn a uncLMon lMbrary
SLep 5: Lhe uncLions
are displayed
SLep 6: use o WhoProc
uncLion
SLep 7: use o PrompL
uncLion
8
You can then reter to either all ot the data by reterencing the vhole array variable, or
you can reter to just one specitic item in the variable by reterencing a single element
(using the subscript, in the array.
You can Lhink o an array as a variable even Lhouh iL diers rom a variable
in LhaL a variable has only one value. An array can conLain mulLiple values
idenLiied by Lhe subscripL. 1hey boLh sLore daLa LhaL can be chaned and
accessed. Arrays and variables are sLored Lemporarily in memory unless wriL-
Len Lo disk.
Data can be placed in an array trom the keyboard or vith positional parameters. Once the
data is in the array, the data can be processed as needed. An advantage ot using an array is
that you can process large amounts ot data in memory by just using the array`s name.
Processing data in memory is much taster than processing data on the hard disk. 1his
makes arrays suitable tor sorting a large amount ot data.You have a script or a tunction
read all the records to an array, process the array, then revrite the data to either the same
tile or a nev tile. 1o complete the same task on a hard disk vould prove much more
time consuming. An example ot processing data in an array in memory is sorting and
searching.You vill learn about sorting and searching data in an array in Chapter 9.
1he items in an array are stored and accessed using their subscripts. Accessing items in
an array is much like going to the back ot your textbook and looking up a term in the
index.You knov the term you vant to locate in the book, but you need the page ret-
erence. 1he page reterence is like the subscriptboth are numerical reterences to the
item you need.
In ligure 8-16, you see vhat an array looks like trom a user`s standpoint. In the tigure,
there are 10 items that are all relatedthey are all animals. (1he decision to place just
10 items is arbitrary., Although the programmer may have input trom users, the pro-
grammer ot the script typically decides hov much data to place in the array. Iook at
some ot the items in the array. Subscript number 3 in the animal array reters to Zebra.
Subscript number 0 reters to Cat.
You could create 100 ditterent variables and name them something like Animal1,
Animal2, Animal3, all the vay to Animal100. Set up as variables, you could only access
each item as shovn in the tolloving example
echo $Animall
echo $Animal2
echo $Animal3 .
With 100 items, this vould not be a very etticient approach. Lsing an array is more etti-
cient because you can use other programming structures to easily loop through the array
8MT
318 CLaTXeV 8 *uRcXMoRs aRH AVVays
DeclaVMRK aR AVVay aRH AssMKRMRK AVVay Values 319
and assign and access values vithin it.1hen, you could turn your list ot animals into the
tolloving statement
for {{num=0, num<=100, num++||
do
echo ${animalnum} # Display one element, or animal, in the array.
done
()CLA6IN+ AN %66AY AND %SSI+NIN+ %66AY :ALU)S
It you vant to create an array and not put any data in it immediately, you declare the
array vith the declare ~a or typeset ~a commands, they are synonymous and are
shell builtin commands. 1hese commands are used to simply create an empty array. It
you vant to create an array and immediately place data in it, you assign a data value to
a location in the array, using the array name and a subscript.
DeclaVMRK aR AVVay
You can create an empty array that can later be used to hold data vith the declare ~a
statement. Because the declare statement can be used to create variables, integers, or
tunctions, you are required to specity the ~a option in order to create an array.You use
this approach it you vant to allov users to input data trom the keyboard or it you vant
to read data in trom another tile. Because you don`t knov the exact data the array vill
contain, it makes sense to simply declare it. Once declared, you can use the read com-
mand to allov a user to place data in the array. 1he general tormat ot the declare ~a
statement is
declare ~a array~name
LlemenL
subscripL
DaLa
value
0
1
2
3
4
5
6
7
8
9
CaL
Do
LlephanL
Zebra
OcLopus
Lion
Kanaroo
Gorilla
Seal
1orLoise
*MKuVe 8-16 AnMmal array
8
1his is vhere array~name is a user-detined name. lor example, in order to create an
array named car vhich can hold various car types, you enter
declare ~a car
Once you`ve created the array, you need to assign values to it.
AssMKRMRK Values Xo XLe AVVay
Once the array is declared, you can input values into it using the subscript.You use the
tolloving method to assign values to elements in the array. It the array is not created,
you can use this method to both create the array and assign values to it.
array~namesuoscr1t~numoer=va1ue
1his is vhere array~name is a user-detined name tor the array.1he square brackets are
required, and they surround the suoscr1t~numoer. 1he equal sign is required to
assign the element in array~name.1he element reterenced by suoscr1t is assigned
to the item specitied by va1ue.
Place quoLes around daLa LhaL conLains LexL or spaces; oLherwise, Lhe shell
cannoL inLerpreL Lhem properly. Do noL puL quoLes around numeric values.
Consider the tolloving example
product0= "Tire"
1his creates an array named product and places the data value 1ire in the tirst, sub-
script, vhich is 0.
You can specity any value to be reterenced by any subscript in any order. 1he tolloving
example places the data 1he Hardvare Store in the array named Store using the sub-
script 3. (Note that it becomes the sixth element because subscripts begin vith 0., 1he
data reterenced by subscript 2 in the array is 1he Cratt Store (it becomes the third
element,. Note the use ot quotes around the data because the data contains spaces. It
you leave ott the quotes, you encounter an error trom the shell.
Store5="The Hardware Store"
Store2="The Craft Store"
It you knov vhat the data is that you vant assigned to your array, you can assign val-
ues to the multiple elements in the array on a single line using the tolloving syntax
array~name= {va1ue1 va1ue2 va1ue2.va1ueu|
Notice that this tormat uses parentheses to surround the values, not brackets. Also, each
item betveen the parentheses is separated by using a space as the delimiter. Lach ot the
values is stored in the array and given a subscript beginning vith 0. Iook at an example
grade={l00 99 85 88 97|
8MT
320 CLaTXeV 8 *uRcXMoRs aRH AVVays
AccessMRK aRH CleaVMRK Values MR aR AVVay 321
In this example, 100 is assigned grade0, 99 to gradel, 83 to grade2, 88 to
grade3, and 97 to grade4.
It you vant to assign elements to specitic subscripts, you can use the tolloving method
grade0=l00
gradel=99
grade2=85
grade3=88
grade4=97
%CC)SSIN+ AND 'L)A6IN+ :ALU)S IN AN %66AY
Once you create an array and assign values to it, at some point in time, you need to
access the data vithin it. 1o reterence or access an element in an array, you must use the
correct subscript associated vith it. Here is the syntax
${array~namesuoscr1t}
1o display the sixth element (subscript 3, in an array named tood, you enter echo
${food5}.
You can also assign a variable to an array element. In the tolloving statement, the vari-
able tooditem is assigned to the sixth element in the array. You could then use echo
$fooditem to display the contents ot tooditem. In this example, tooditem is not an
array but a variable that contains a single value trom the array.
fooditem=${food5}
Next you vill create a script named 1ools that creates an array and assigns and accesses
values in the array.
1o dIclarI an arra] and assMgn and accIss valuIs Mn thI arra]
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named 1ools in the $HOME/bin directory.
3. Insert the tolloving lines ot code to create the array and assign values to the
tirst three elements
declare -a Tool
Tool0]="Wrench"
Tool1]="Hammer"
Tool2]="Saw"
4. Nov insert the tolloving lines ot code to display the values you`ve just assigned
echo ${Tool0]}
echo ${Tool1]}
echo ${Tool2]}
8
3. Save the script, and then close the editor.
6. Make the script executable, and execute the script. ligure 8-17 shovs the
output ot the execution ot the 1ools script. In this case, the values tor the
1ool array are listed Wrench, Hammer, and Sav.
7. Close your vindov, and then log out.
You could revrite the last three echo statements ot the previous exercise using a loop-
ing structure. 1he advantage ot using a looping structure is that you save keystrokes it
you have many array elements to display. Lxamine the tolloving 1ools script that has
been revised to replace the last three echo statements vith one echo statement using
a for loop.
declare ~a Tool
Tool0="Wrench"
Tooll="Hammer"
Tool2="Saw"
for num in 0 l 2
do
echo ${Toolnum}
done
At tirst glance, it does not appear that you have saved very much in the vay ot entering
text in the script. Atter all, you had three echo statements and nov you have tour state-
ments to replace those three. Hovever, it you had 100 array elements to display, then
using the for statement is more productive.
*MKuVe 8-17 OuLpuL o Lhe 1ools scrMpL
322 CLaTXeV 8 *uRcXMoRs aRH AVVays
AccessMRK aRH CleaVMRK Values MR aR AVVay 323
ImToVXaRce of UsMRK &Vaces
1he braces, { } in ${array~namesuoscr1t} are required to avoid contlicts.
1he use ot braces serves to protect the square brackets vhen reterencing an element in
an array. Pemember in Chapter 4 that the use ot braces, as in ${x}, reters to the con-
tents ot x.Without the braces, the square brackets, (,, are displayed on the screen
along vith inaccurate results. ligure 8-18 shovs an array named tood being assigned
six values in the tirst statement. Next, the sixth element is accessed using the statement
echo ${food5}.You can see that the correct text apple is displayed on the screen.
In the last statement, echo $food5, the braces are lett ott. Notice that the text
sandvich[3| is displayed, vhich is not the correct result.1he tirst element in the array,
sandvich, is displayed as vell as the literal meaning ot the square brackets and the
subscript, instead ot using the bracket`s meaning to access a data value in an array.
Another reason to use braces is to avoid contlicts vith pattern-matching expansion.You
can use pattern-matching symbols, ., to match a range ot characters vhen using path-
name expansion. (1his topic vas discussed in Chapter 4,. Because you use square brack-
ets in pathname expansion and in array substitution, you need a vay to protect the
meaning ot the square brackets vhen reterencing an array element.
AVMXLmeXMc OTeVaXMoRs aRH VaVMable Name SubsXMXuXMoR
You can use arithmetic operations and variable name substitution to determine a sub-
script number. In ligure 8-19, the contents ot the tood array are displayed using a vari-
ety ot methods including name substitution and arithmetic operations. Although this is
*MKuVe 8-18 1he MmporLance o usMnK braces when accessMnK an elemenL Mn an array
8
not necessarily a practical implementation ot arithmetic operations, vhen you get to
Chapter 9, vhich deals vith sorting and searching, you vill need to have an under-
standing ot these concepts.
1he statement, echo ${foodl+2} is equivalent to echo ${food3} due to the
addition operation, thus lettuce is displayed. 1he statement, echo ${food6~l} is
equivalent to echo ${food5}, again due to the arithmetic operation ot subtraction,
and apple is displayed. You can also see that a variable named 1 is set to 4. So, the
statement, echo ${foodT} using name substitution is equivalent to echo
${food4} and carrots is displayed. linally, a division operation, echo ${food4 /
2}, results in spinach being displayed.
6efeVeRcMRK all XLe )lemeRXs MR aR AVVay
You can reterence all ot the elements in an array by using the asterisk symbol enclosed
in the square brackets.1his is usetul vhen you vant to display the contents ot the entire
array. 1he echo ${food*} statement displays all ot the elements in the array.
1o help you remember LhaL Lhe asLerisk allows you Lo reerence all Lhe ele-
menLs in an array, Lhink back Lo ChapLer 4 and Lhe use o Lhe asLerisk sym-
bol Lo expand Lo all characLers. So, simply equaLe * wiLh "all." 8MT
*MKuVe 8-19 Lxamples o varMable name subsLMLuLMon and arMLhmeLMc operaLMons Mn an array
32 CLaTXeV 8 *uRcXMoRs aRH AVVays
AccessMRK aRH CleaVMRK Values MR aR AVVay 325
DeXeVmMRMRK XLe NumbeV of )lemeRXs MR aR AVVay
You can determine the number ot elements in the array by placing the number sign, #,
immediately betore the array`s name, as in the tolloving statement
echo ${#food*}
1his is usetul tor determining hov large the array is, at least in terms ot the number ot
elements.
You can use a looping structure, such as the for statement, to loop through the elements
in an array and process each element. lor example, look at the code shovn in ligure 8-20.
In the for statement, the variable num is compared to the number ot elements in the array,
specitied by `echo ${#food*}` vhich has a value ot 3 (remember it starts vith 0,
because there are six elements in the array. As long as num is less than the number ot ele-
ments in the array, then num is incremented until it reaches the number ot elements.
Lsing the number ot elements in the array in this manner is very tlexible because it dis-
plays all ot the elements in the array regardless ot the amount ot data.
DeXeVmMRMRK XLe LeRKXL of aR )lemeRX MR aR AVVay
You can display the length ot one data value in the array it you replace the asterisk in
the preceding example vith the subscript number ot the element. So, it the third ele-
ment in the array is spinach, then the echo ${#food2} statement vill display the
number 7, because spinach is seven characters long.
*MKuVe 8-20 9sMnK Lhe number o elemenLs Mn an array Mn a loopMnK sLrucLure
8
1his is usetul tor determining it an element is ot a minimum or maximum length. One
reason you might vant to use this is to make sure a user has entered an element. lor
example, you could test this statement to determine vhether a user entered a value or
not. In the tolloving code segment, the length ot the third element is tested tor a length
ot zero. It the length is zero, then the contents ot subscript 2 in the tood array is empty,
and thus, an appropriate message is displayed indicating so. It the length is nonzero, then
the contents ot subscript 2 do indeed contain data and an appropriate message is dis-
played indicating there is data.You could use this code segment in a script to test vhether
or not an array item contains data or not.
if `echo $#{food2}` ~eq 0
then
echo "Element referenced by subscript 2 is empty."
else
echo "Element referenced by subscript 2 contains data."
fi
8Le VIEH SXaXemeRX aRH AVVays
You can use the read statement to enter data into an array trom the keyboard. 1his
allovs greater tlexibility by alloving users to enter data. All you need to do is vrite the
script to manipulate the data.
Next you vill create a script named ArrayPead that accepts text you enter trom the key-
board and displays your data.
1o crIatI a scrMpt that rIads data fron thI kI]board and dMspla]s thI data
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named Arra]RIad in the $HOME/bin directory.
3. Insert the tolloving lines to read the data trom the keyboard
read -p "Enter total number of entries: " total
for {{n=0, n < $total, n++}}
do
read -p "Enter value: " entries$n]
done
4. Insert the tolloving lines ot code to display the data previously read trom the
keyboard
for {{n=0, n < $total, n++}}
do
echo "Value $n is ${entriesn]}"
done
3. Save the script, and then close the editor.
326 CLaTXeV 8 *uRcXMoRs aRH AVVays
CVeaXMRK 6ecoVHs UsMRK AVVays 327
6. Make the script executable, execute the script, and then enter 3 vhen
prompted tor the number ot entries, and enter 1, 2, and 3 vhen prompted
tor the values. Be sure to press Lnter atter each entry. See ligure 8-21. 1he
array items are displayed on the screen.
7. Lxecute the script again, and then enter vhen prompted tor the number ot
entries, and enter 100, 90, 99, 80, and 87 vhen prompted tor values. Be sure to
press Lnter atter each entry. 1hese array items are displayed on the screen. See
ligure 8-21. Notice hov easy it is to allov a user to enter data into an array.
8. Close your vindov, and then log out.
'6)A8IN+ 6)CO6DS 9SIN+ %66AYS
As you knov, you can use arrays to store variables, but it`s important to note that these
variables can also be complete records. Pecall that an array is stored temporarily in mem-
ory. By placing records into an array, you are accessing the data much taster than it you
vere to access them trom disk. 1his is because memory access is taster than disk access.
lor example, say that Denise Chyan-McConnell`s dryvall business has several employ-
ees vorking tor it. Lach employee record consists ot the tolloving tields
Identitication number
Name
Salary
*MKuVe 8-21 ReadMnK daLa MnLo an array usMnK a loopMnK sLrucLure
SLep 6: array values are
displayed
SLep 7: array values are
displayed
8
328 CLaTXeV 8 *uRcXMoRs aRH AVVays
Lach record is a data element in the array. A subscript reterences one record. Here is
vhat tvo sample records look like
l00:"DuJuan Sing":56000
l0l:"Mary~Lou Buttercup":50000
In these records, the colon has been chosen to act as the tield separator.You cannot use
a space because the space is used to delimit the elements in an array. 1he use ot quotes
surrounding the name allovs spaces to exist in the name, othervise, the shell assumes
they are separate array elements.
Assume that the data tor subscript 0 is l00:"DuJuan Sing":56000 and the data tor
subscript 1 is l0l:"Mary~Lou Buttercup":50000. Here`s hov the records appear
in the emp array (Pemember, there are three tields per record, and one record is reter-
enced by one subscript.,
emp={100:"DuJuan Sing":56000 101:"Mary~Lou Buttercup":50000 |
Although the tields in each record are arranged in one order, you might vant to display
them in a ditterent order, tor example, the name tolloved by the salary and then the
identitication number. Or, you could just display the name and the salary.1o accommo-
date this, you need to separate each tield vithin each record.You can use the cut com-
mand to get each tield trom a record. Because the colon symbol is used to separate
individual tields in the array, the cut command can be used to separate tields delimited
by the colon.
Iook at the identitication number tield as an example.
id=`echo ${emp$count} ] cut ~d: ~fl`
1he identitication number, or id, is the tirst tield ot each record.You need to tirst echo
the contents ot an element (a record in this case,, then use the pipe operator to send the
data to the cut command to cut the tirst tield, and then use the colon as a delimiter to
separate the tields. In the tolloving statement, the contents ot an array element tor a sub-
script named count is echoed to the cut command. 1he ~d: option tor cut means to
delimit the tields using a colon.1he ~fl option tor cut cuts the tirst tield, vhich is id.
1hus, this command takes the record contained in the array named emp at subscript
position count, cuts the tirst tield using the delimited colon, and places the contents in
the variable named id. 1he name and salary are cut similarly.
Next you vill create an array ot records, and then cut the tields vithin each record. Lach
record occupies one subscript position in the array.
1o crIatI a scrMpt that dMspla]s fMIlds fron rIcords Mn an arra]
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named Arra]RIcords in the $HOME/bin directory.
CVeaXMRK 6ecoVHs UsMRK AVVays 329
3. Insert the tolloving lines ot code to create the array and set the variable max
to the total number ot elements in the array
# The array emp holds the records
emp={100:"DuJuan Sing":56000 101:"Mary-
Lou Buttercup":50000 103:"Joe Brown":45000
104:"Mary Seoul":67000 }
max=${#emp*]} # Max eguals the total number of elements
4. Insert the tolloving lines ot code to create the loop to process all the records
in the array. 1he variable count is used to increment the items in the array. It
begins at 0 and is incremented until it reaches the variable named max.
for {{ count=0, $count < $max , count++ }} # Count is the subscript
do
3. Insert the tolloving lines ot code to set each ot the tields to variable names
that can be used
id=`echo ${emp$count]} [ cut -d: -f1` # Field 1
name=`echo ${emp$count]} [ cut -d: -f2` # Field 2
salary=`echo ${emp$count]} [ cut -d: -f3` # Field 3
6. Insert the tolloving lines ot code to display all ot the tields and terminate
the loop
echo "The id of $name is $id and the salary is $salary."
done
7. Save the script, and then close the editor.
8. Make the script executable, and execute the script. See ligure 8-22. All ot the
records in the array are displayed.You could modity the script to include
additional records and rerun it vithout changing anything else. Because the
variable max contains the maximum number ot array elements, it alvays
retlects the correct number.
9. Close your vindov, and then log out.
8
'HA48)6 7UMMA6Y
lunctions are miniprograms that can be executed trom a shell or trom vithin a
script. 1hey allov you to reuse program code and they reduce redundancy because
they can be called multiple times. Because tunctions are modular, you can trou-
bleshoot a program quickly.
1he parts ot a tunction include the name ot the tunction and the list ot the com-
mands the tunction pertorms. When creating a tunction, you must precede the
tunction name vith either the text tunction or tollov it vith lett and right
parentheses.You must also use a lett brace, ({,, and a right brace, (},, to begin and
end the tunction.
A tunction is called in a script by placing the name ot the tunction vhere you
vant it used. lunctions are tlexible because they allov you to pass data to them
during the tunction call.Variables detined in tunctions can be either local or global.
A local variable can only be detined vithin a tunction. A local variable can only be
changed vithin the tunctionhence it is local to the tunction. A global variable
can be changed anyvhere in the script.You can determine vhether or not a tunc-
tion succeeded by using the return keyvord.You can export a tunction so it can
be used in a subshell.
You can place tunctions that are trequently used in a tunction library. A tunction
library is a tile that contains tunctions. By creating a tunction library, you allov
other users to utilize the tunctions.You use the source command to access the
*MKuVe 8-22 ProcessMnK records Mn an array
All Lhe records in Lhe
array are displayed
330 CLaTXeV 8 *uRcXMoRs aRH AVVays
6evMew QuesXMoRs 331
tunction library. It the script only contains tunctions, then running the source
command makes the tunctions available to users.
An array is a variable that holds data as a series ot elements. 1he data is accessed
using a subscript vhich is an integer. Subscripts start numbering at zero, there can
be an unlimited number ot subscripts in any given array.You can reter to all the
data or individual data elements by using a subscript. 1he advantage ot an array is
that it can be held in memory.
Arrays can be created vith the declare~a statement. An array is also created
vhen assigning a value to a subscript, as in array~namesuoscr1t=va1ue or
array~name={va1ue1va1ue2.va1ueu|.You can access individual items by
reterencing the subscript number that corresponds to the array element, as in echo
$array~namesuoscr1t.
You can create and access records vithin an array.You need to use a separator such as
the colon to delimit the tields. When using an array this vay, the elements in the
array represent an entire record.1he advantage ot accessing records in an array is
improved pertormance because the records are held in memory until vritten to disk.
6)VI)W 5U)S8IONS
1. A is a set ot statements that is considered a miniprogram.
a. tunction
b. array
c. tunction library
d. block
2. Which ot the tolloving commands is used to create an array
a. create
b. declare
c. function
d. source
3. You use the command to call a tunction library tile.
a. create
b. declare
c. function
d. source
8
4. Which ot the tolloving commands is used to display all variables
a. create
b. typeset
c. function
d. source
3. You use the command to create a tunction named Goals.
a. unsetGoals
b. declare~aGoals
c. functionGoals{|
d. sourceGoals
6. Which ot the tolloving commands is used to remove a tunction named Goals
a. unsetGoals
b. declare~aGoals
c. functionGoals{|
d. sourceGoals
7. You use the statement to display all the values in an array
named Beaches.
a. echo${Beaches0}
b. echo${Beaches*|
c. echo${Beaches#}
d. echo${Beaches*}
8. A reters to the element number in an array.
a. call
b. data value
c. subscript
d. return value
9. is the process ot breaking a programming task into
smaller pieces.
a. lunction calling
b. Subscripting
c. Indexing
d. Modularization
332 CLaTXeV 8 *uRcXMoRs aRH AVVays
6evMew QuesXMoRs 333
10. A activates a tunction.
a. tunction call
b. return value
c. subscript
d. tunction module
11. Which ot the tolloving commands is used to display the length ot the data value
located at subscript 3 in the array named Beaches
a. echo${Beaches5}
b. echo${#Beaches4}
c. echo${#Beaches5}
d. echo${@Beaches*}
12. Which ot the tolloving commands is used to display the tirst value in the array
named Beaches
a. echo${Beaches0}
b. echo${Beachesl}
c. echo${Beaches2}
d. echo${Beaches*}
13. You use the command to declare a variable so it can only be
used in a tunction.
a. global
b. function
c. declare~a
d. source
14. A value is to a tunction vhen the tunction is given the value
to process.
a. called
b. returned
c. passed
d. evaluated
13. Which ot the tolloving commands is used to display the total number ot data val-
ues in the array named Beaches
a. echo${Beaches}
b. echo${*Beaches#}
c. echo${#Beaches*}
d. echo${@Beaches*}
8
16. Which ot the tolloving declares an array named States vith the elements llorida,
Georgia, Maine, Montana, and Alabama
a. states={FloridaGeorgiaMaineMontanaAlabama|
b. states={FloridaGeorgiaMaineMontanaAlabama|
c. states0l234={FloridaGeorgiaMaineMontana|Alabama
d. function{|={FloridaGeorgiaMaineMontanaAlabama|
17. What is the result vhen the tolloving tunction is executed
Functionairplane{}
{
echo"Airplane"
|
airplane$l
a. a syntax error
b. 1he tirst positional parameter is displayed.
c. 1he text Airplane is displayed.
d. 1he text Airplane s1 is displayed.
18. What is the result vhen the tolloving tunction is executed
Functionairplane{|
{
echo$l
}
airplane$l
a. a syntax error
b. 1he tirst positional parameter is displayed.
c. 1he text Airplane is displayed.
d. 1he text s1 is displayed.
19. What is the result vhen the tolloving script is executed
arrayl={abcde|
echo${arrayl3+l}
a. a syntax error
b. 1he letter b is displayed.
c. 1he letter d is displayed.
d. 1he letter e is displayed.
33 CLaTXeV 8 *uRcXMoRs aRH AVVays
HaRHs-oR 4VoNecXs 335
20. What is the result vhen the tolloving script is executed
arrayl={abcde|
echo$arrayl{0}
a. a syntax error
b. 1he letter a is displayed.
c. 1he letter d is displayed.
d. 1he letter e is displayed.
,ANDSON 46OJ)C8S
4VoNecX 8-1
In this project, you vill create an array and manipulate data vithin the array.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named ProNIct8-1 in the $HOME/bin directory.
3. At the command line, enter the tolloving statements
Array0]=5
Array1]=10
Array4]=2
Array2]=100
Array3]=7
4. Display all the elements in the array using one echo command, and then record
the command that you used.
3. What is ditterent about the order ot the items entered compared to the order in
vhich they are displayed
6. Insert the tolloving lines ot code to use calculations and variables to determine
the subscript value
{{t=3}}
echo${Arrayt]}
echo${Array{t+1}/2]}
echo${Array${Array4]}]}
Array5]=`expr${Array1]}+${Array3]}`
echo${Array5]}
7. Save the script, close the editor, make the script executable, and then execute
the script.
8. Pecord the results.
9. Give an explanation vhy each value vas displayed.
10. Close your vindov, and then log out.
,ERHWSR
4VSNIGX
8
4VoNecX 8-2
In this project, you vill create a tunction to display vhether a protit, loss, or breakeven
occurs vhen entering Sales and Costs. A tunction is also used to read the Sales and Costs
amounts by quantity.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named ProNIct8-2 in the $HOME/bin directory.
3. Insert the tolloving lines ot code
function GetData {}
{
read -p "Enter Sales Amount: " Sales
read -p "Enter Costs: " Costs
}
function BELP {}
{
{{Sales=$1}}
{{Costs=$2}}
{{Net=$Sales - $Costs}}
if $Net -eg "0" ]]
then
echo "Profits and Costs are egual - breakeven"
elif $Net -gt "0" ]]
then
echo "Profit of: " $Net
elif $Net -lt 0 ]]
then
echo "Loss of " $Net
fi
}
GetData
BELP $Sales $Costs # Call the BELP {BreakEvenLossProfit}
function
4. Save the script, close the editor, and then make the script executable.
3. Lxecute the script, input 1000 tor Sales and 2000 tor Costs vhen prompted, and
then record the output.
6. Pun the script, input 80000 tor Sales and 27000 tor Costs vhen prompted, and
then record the output.
7. Pun the script, input 0000 tor Sales and 0000 tor Costs vhen prompted, and
then record the output.
8. Close your vindov, and then log out.
4VoNecX 8-3
In this project, you vill display a message it a value entered into the array is blank.1vo tunc-
tions vill be called, one to read the data and another to check the data. 1he goal ot this
project is to help you implement tunctions and arrays and test the length ot data elements.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
336 CLaTXeV 8 *uRcXMoRs aRH AVVays
HaRHs-oR 4VoNecXs 337
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named ProNIct 8-3 in the $HOME/bin directory.
3. Insert the tolloving lines ot code
ReadEntries {}
{
read -p "Enter total number of entries " tot # Read
total values.
for {{n=0, n < $tot, n++}} # Loop and read values.
do
read -p "Enter value " entries$n]
done
}
CheckForBlanks{}
{
for {{n=0, n < $tot, n++}}
do
if `echo ${#entriesn]}` eg 0 ]] # If
element length 0, assume blank.
then
echo "Value" $n "is blank"
else
echo "Value" $n "is" ${entriesn]}
fi
done
}
ReadEntries
CheckForBlanks
4. Save the tile, close the editor, and then make the script executable.
3. Pun the script and enter 4 as the number ot entries, and then insert the tolloving
tour values vhen prompted frog, dog, press LntIr tor the third value, and 400.
6. Pecord the output.
7. Perun vith ditterent values, and then record your tindings.
8. Close your vindov, and then log out.
4VoNecX 8-
In this project, you vill use an array to hold directory names.You vill test vhether each
directory exists and it so, a tree listing ot the directory is displayed.1his project reintorces
the use ot arrays.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named ProNIct8-4 in the $HOME/bin directory.
3. Insert the tolloving lines ot code
declare -a dir
,ERHWSR
4VSNIGX
8
dir={ cats dogs birds snakes cats/large cats/small }
# The directories.
max=${#dir*]}
for {{ num=0, num < $max, num++ }}
do
if ! -d ${dirnum]} ]] # If
directory does not exist create and perform a tree
listing.
then
echo "Creating directory " ${dirnum]}
mkdir ${dirnum]}
fi
done
4. Save the script, close the editor, and then make the script executable.
3. Lxecute the script, and then record the output.
6. Close your vindov, and then log out.
4VoNecX 8-5
In this project, you vill vork vith the scope ot variables.You vill create a tunction vith
a locally detined array and a globally detined array.You vill then attempt to access the
contents ot the arrays inside and outside the tunction.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named ProNIct8- in the $HOME/bin directory.
3. Insert the tolloving lines ot code
function Arrays{}
{
local -a LocalArray # Locally defined array.
LocalArray0]=0 # Set local array values.
LocalArray1]=1
LocalArray2]=2
echo "Local inside function" ${LocalArray*]}
echo "Global inside function" ${GlobalArray*]}
}
GlobalArray0]=100 # Set global array values.
GlobalArray1]=101
GlobalArray2]=102
Arrays # Function call
echo "Local outside function" ${LocalArray*]}
echo "Global outside function" ${GlobalArray*]}
4. Save the script, close the editor, make the script executable, and then execute
the script.
3. Pecord the output. Why can`t you see the contents ot the local array outside ot
the tunction
6. Close your vindov, and then log out.
,ERHWSR
4VSNIGX
338 CLaTXeV 8 *uRcXMoRs aRH AVVays
HaRHs-oR 4VoNecXs 339
4VoNecX 8-6
In this project, you vill populate an array vith as many positional parameters as the user
enters on the command line.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named ProNIct8- in the $HOME/bin directory.
3. Insert the tolloving lines ot code
PopulateArray{}
{
max=$# # Max eguals total number of positional parameters.
for {{i=0, i < $max, i++}}# Loop through
array for all parameters.
do
values$i]=$1 # Array element eguals positional
parameter.
shift 1 # Shift the parameters to get the next
parameter.
done
}
ListArray{}
{
echo ${values*]} # Display all elements in the array.
}
PopulateArray $* # Function Call with all positional
parameters.
ListArray # Function Call to display array contents.
4. Save the script, and then close the editor.
3. Make the script executable, execute the script, and then input the tolloving posi-
tional parameters 4, 1, 0, 11, 200, and 1hI Lnd!.
6. Pecord the output.
7. Lxecute the script again, this time passing no positional parameters.
8. Lxecute the script one last time, and then input the tolloving positional parame-
ters cars, planI, trucks, fIncIs, and plants.
9. Pecord the output.
10. Close your vindov, and then log out.
4VoNecX 8-7
In this project, you vill create a tunction that uses the date command to display the
date in either ulian tormat (numeric day,, the date in MMDDYYYY tormat, or the
time in HMS (hours, minutes, and seconds, tormat. A positional parameter ( or j
tor ulian, 1 or t tor 1ime tormat, and M or m tor MMDDYYYY tormat, is
passed to the tunction.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
8
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named ProNIct8-7 in the $HOME/bin directory.
3. Insert the tolloving lines ot code
function DateFun{}
{
if $# -eg 1 ]]
then
case "$1" in
J[j} echo "The Julian date including the
year is:" `date +%Y%j`
,,
T[t} echo "The time is:" `date +%X`
,,
M[m} echo "The date in MM/DD/YYYY
format is:" `date +%x`
,,
* } echo "Invalid date format. Use J, T or M"
esac
else
echo "Invalid number of parameters. Use J, T or M"
fi
}
DateFun $1
4. Save the script, and then close the editor.
3. Make the script executable, execute the script, pass M as the positional parameter
vhen prompted, and then record the output.
6. Lxecute the script, pass t as the positional parameter vhen prompted, and then
record the output.
7. Lxecute the script, pass ) as the positional parameter vhen prompted, and then
record the output.
8. Lxecute the script, pass a as the positional parameter vhen prompted, and then
record the output.
9. Lxecute the script, and then pass no positional parameter vhen prompted. What
happens vhen you do not pass a positional parameter to the script
10. Close your vindov, and then log out.
4VoNecX 8-8
In this project, you vill create a menu in vhich you can enter grades to be averaged.
1he grades are to be placed in an array.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script, named ProNIct8-8 in the $HOME/bin directory.
3. Insert the tolloving lines ot code
declare -a grade
Ans="Y"
,ERHWSR
4VSNIGX
30 CLaTXeV 8 *uRcXMoRs aRH AVVays
HaRHs-oR 4VoNecXs 31
while $Ans = "Y" ]]
do
read -p "Enter number of grades " Max
for {{num=0, num < $Max, num++}}
do
read -p "Enter value" grade$num]
{{tot=$tot+${grade$num]}}}
done
{{avg=$tot/$Max}}
echo "The average is " $avg
read -p "Do you want to continue? Y/N" Ans
{{avg=0}}
{{tot=0}}
done
4. Save the script, and then close the editor.
3. Make the script executable, execute the script, and vhen prompted, input 3 tor
the maximum number ot grades tolloved by the grades 100, 100, and 90.
6. Pecord the result.
7. Press Y to continue.
8. Perun the script, input 4 tor the maximum number ot grades tolloved by the
grades 80, 88, 90, and 77.
9. Pecord the result.
10. Press Y to continue.
11. Perun the script, and vhen prompted, input 2 tor the maximum number ot
grades tolloved by the grades 80 and 88.
12. Pecord the result.
13. Press N to stop.
14. Close your vindov, and then log out.
4VoNecX 8-9
In this project, you vill create an array ot records and manipulate the tields contained
in a record.You vill also pertorm calculations based upon tvo tields, then accumulate
totals and display the results.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script, named ProNIct8-9 in the $HOME/bin directory.
3. Insert the tolloving lines ot code
prod={Hammers:10:20 Saws:12:5 Nails:100:2 Drills:75:3 }
max=${#prod*]}
for {{ count=0, $count < $max , count++ }}
do
,ERHWSR
4VSNIGX
8
product=`echo ${prod$count]} [ cut -d: -f1`
price=`echo ${prod$count]} [ cut -d: -f2`
guantity=`echo ${prod$count]} [ cut -d: -f3`
{{total = $price * $guantity}}
echo "Total for \$$product is \$$total"
{{GrandTotal = $GrandTotal + $total}}
done
echo "Grand Total is \$$GrandTotal for $max items. "
4. Save the script, close the editor, and then make the script executable.
3. Lxecute the script, and then record the output.
6. Close your vindov, and then log out.
'AS) 46OJ)C8S
Case 8-1
You are asked to implement the 1MI menu script that you created in Case 1 ot Chapter 7,
but this time you are to use tunctions. Also, create the tunctions in a tunction library tile,
and place it in an appropriate directory.
Case 8-2
In this case, you vill use tunctions, looping structures, arrays, decision statements, calcu-
lations, and other commands necessary to complete the tolloving tasks
1. Lse an array to hold a student record vith a name and three grades, tor example
"MaudeTedders":l00:88:90.
2. Lse the necessary commands to cut the tields into the name and grades tields.
3. Lse another array to contain the three grades. lor example
Gradel=necessary statements to get the f1rst grade
Grade2=necessarystatementstogetthesecondgrade
Grade3=necessarystatementstogettheth1rdgrade
4. 1ake a numeric average ot the three grades.
3. Convert the numeric average to a letter grade using this scale
A is 90 to 100
B is 80 to 89
C is 70 to 79
D is 63 to 69
l is 0 to 64
6. lor each student record, display the student name, numeric average, and letter grade.
7. You must implement at least one tunction vithin the script.
'EWI
4VSNIGX
'EWI
4VSNIGX
32 CLaTXeV 8 *uRcXMoRs aRH AVVays
33
',%48)6

%(:%2')( 7,)00 463+6%11-2+


-RXLMWGLETXIV]SY[MPP
-QTPIQIRXEFYFFPIWSVX
-QTPIQIRXE7LIPPWSVX
'SQTEVIXLIFYFFPIWSVXERH7LIPPWSVX
-QTPIQIRXWIUYIRXMEPWIEVGLXIGLRMUYIW
-QTPIQIRXFMREV]WIEVGLXIGLRMUYIW
9RHIVWXERHXLILIVIHSGYQIRX
9RHIVWXERHJMPIEGGIWW
:EPMHEXIHEXE
8
hMs chapter tocuses on advanced shell programmMng concepts You vMll
expand your knovledge ot arrays and tunctMons by MmplementMng sort
and search technMques At the heart ot processMng data Ms accessMng records on
dMskYou vMll be able to read records trom a tMle and vrMte records to a tMle
lMnally, you vMll learn hov to pertorm data valMdatMon technMques so that
Mmproper data Ms not processed
-M4L)M)N8IN+ A &U&&L) 7O68
You learned in Chapter 2 that you can use the sort command to organize data.
Lnderstanding hov to implement your ovn sorting mechanism can also provide a
practical application ot arrays and tunctions.
1here are a variety ot techniques used to sort data.1he tvo discussed in this chapter are
the bubble sort and the Shell sort. 1he bubblI sort uses an algorithm to sort the data.
An algorMthn is a method or tormula used to solve a problem. 1he bubble sort
algorithm compares adjacent elements in an array and sorts them in either ascending or
descending sort order. With an ascending sort, items are sorted trom lover to higher.
With a descending sort, they are sorted trom higher to lover. lor example, the numbers
1, 2, 3, 4, 3 are sorted in ascending order, vhile 3, 4, 3, 2, 1 are sorted in descending order.
1he term bubble in bubble sort comes trom the tact that in an ascending sort, the lov
order values in sequence bubbleto the top ot the array. In a descending sort, the high order
values in sequence bubble to the top. Once the bubble sort completes, all ot the data
is sorted.
1he bubble sort can be used to sort numbers or characters. AdNacInt IlInInts are sep-
arated by a subscript value ot 1. So, $al and $a2 vould be considered adjacent
elements because their subscripts values, 1 and 2, ditter by 1. It you are implementing
an ascending sort and $al equals the number 4 and $a2 equals the number 3, they
are svapped so they can be in the correct sort order. Consider the tolloving overviev
ot the pseudocode tor the bubble sort algorithm
;hiie there are eiements in the arra
(o
Compare ^ ano (^ 1) oata eiements
If ^ > ^ 1 lHL^
:uap ^ ano ^ 1
Lnoif
In.rement ^
(one
While you can use the bubble sort to sort data elements in an array in descending order,
in this section you vill tocus on sorting data in ascending order vith the bubble sort.
1he bubble sort uses tvo loops, an outer loop and an inner loop, an if statement to
compare the elements, and a tunction named swap to svap the tvo elements it they are
out ot sort order. 1hese tvo loops are shovn in ligure 9-1.
3 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
ImTlemeRXMRK a &ubble SoVX 35
1he term pass is used to describe the comparison ot the elements vithin the loop trom
the beginning ot the array to the end.1he data is not necessarily sorted on a single pass.
It may take several passes to sort all the data. A pass is comprised ot multiple iterations
using the for statement. 1he bubble sort cannot possibly sort all adjacent items on a
single pass. So, it makes multiple passes adjusting vhich adjacent elements to compare
and svapping them accordingly.
1he outer loop shovn in ligure 9-1, for {{ p = l, p <= $pass, p++ ||, controls
the overall number ot passes through the array.1he outer loop is pertormed tor the number
ot elements in the array less one.1his is because on the tirst pass, the largest valued element
is in its proper positionlast. So, there is no need to compare the last element in subsequent
passes. In ligure 9-1, the variable p controls the overall number ot loop passes. It is
alvays set to one.
lor every outer loop pass, the inner loop is pertormed pass minus p times. 1his is
accomplished in the for statement for {{ i = 0, i <= {{$pass~$p||, i++ ||.
Here, the variable p is subtracted trom pass because the inner loop has to do one less
comparison on the current pass because the previous pass placed the highest value in its
proper place, thus, it is lett vith last minus one.
1he inner loop is used to pertorm the iterations ot a pass. It includes the
if ${a$i} > ${a`expr $i + l`} statement to compare tvo adjacent
items.1his is vhere the bubbling ettect occurs. It the contents ot i are greater than the
contents ot i plus one, then the tunction named svap is called vith the tvo values in
the statement swap $i `expr $i + l`. 1he heart ot the bubble sort is the svap
tunction. 1he svap tunction accepts the tvo elements as positional parameters and uses
a temporary holding variable name 1 to arrange the elements so that i is nov less
than i plus one. At the completion ot an inner loop pass, the greater ot the tvo numbers
is in its correct position.
for {{ p = 1, p <= $pass, p++ }}
do
for {{ i = 0, i <= {{$pass-$p}}, i++ }}
do
if ${a$i]} > ${a`expr $i + 1`]} ]]
then
swap $i `expr $i + 1`
fi
done
done
OuLer loop (code in
unshaded area) o Lhe
bubble sorL
lnner loop (code in shaded
area) o Lhe bubble sorL
1esLs adjacenL iLems
FuncLion is called i Lhe
elemenLs are ouL o order
*MKuVe 9-1 Loops used by Lhe bubble sorL
9
ligure 9-2 shovs a screenshot ot the bubble sort in action. lirst, the unsorted array is
displayed, and then the bubble sort passes are displayed to shov you vhat occurs at each
pass. linally, the sorted array is displayed.You can see that in each pass the largest value is
moved to its proper place. In Pass 1, the number 9 is moved to the last position. In Pass 2,
the number 8 is moved to its proper position. In Pass 3, the number 7 is moved to its
proper position, and so on. In the last pass, all the numbers are in their correct sort order.
In the next example, the bubble sort is used to sort the letters ot the alphabet. Ietters
are sorted using their ASCII sequence number. 1his is called the collatMng sIquIncI.
In the ASCII collating sequence, the letter a is assigned a lover valued number than the
letter z vhich is vhy the letters can be sorted. So, you can say that a is lover than
z or that z is higher than a.1he sort actually occurs on the number representing
the letter rather than on the letter itselt.
In ligure 9-3, the 26 letters ot the alphabet are sorted.You can really see the bubbling
ettect here. Notice the letter a in each pass. lrom one pass to the next, you can vatch
the letter a move tovards the lett or up in the array, or closer to subscript zero. Also,
at each pass, the highest letter moves tovards the right, or bottom, ot the array. Notice
the number ot passes, 23, this is equal to the number ot values minus one.
Next you vill implement the bubble sort to sort a list ot items you could purchase at a
clothing store.
*MKuVe 9-2 8ubble sorLMnK 10 numbers
36 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
ImTlemeRXMRK a &ubble SoVX 37
1o crIatI thI bubblI sort
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a tile named BubblISortClothIs in your $HOME/bin directory.
3. Insert the tolloving lines ot code to create the svap tunction
# The Bubble Sort
swap{}
{
local T=${a$1]}
a$1]=${a$2]}
a$2]=$T
}
4. Insert the tolloving lines to assign elements to the array, display various output,
and set necessary variables
a={ shirt belt shoes hat socks tie dress } # The items
to be sorted.
echo "The unsorted array"
echo ${a@]} # Display all the items in the array.
echo "The sort passes"
*MKuVe 9-3 8ubble sorLMnK o Lhe 26 leLLers o Lhe alphabeL
9
n=${#a@]} # The variable "n" eguals the
maximum number of elements in the array.
{{pass=$n - 1}} # The variable "pass" eguals one less
than the total number of elements used in the outer loop.
3. Insert the tolloving lines to create the outer and inner loops
for{{p=1,p<=$pass,p++}}
do
for{{i=0,i<={{$pass-$p}},i++}}
do
if${a$i]}>${a${expr$i+1}]}]]#Compare
twoadjacentitems.
then
swap$i${expr$i+1}#Ifunsorted,
swapthetwoadjacentitems.
fi
done
echo"Pass"$p":"${a@]}#Displaythearrayateachpass.
done
6. Insert the tolloving lines to display the sorted array
echo "The sorted array"
echo ${a@]}
7. Save the script, and then close the editor.
8. Make the script executable, and then execute the script. 1he array ot clothes
is displayed in sorted order.
9. Close your vindov, and then log out.
-M4L)M)N8IN+ A 7H)LL 7O68
1he bubble sort is etticient tor small amounts ot data. Hovever, tor larger amounts ot
unsorted data, say over 23 data elements, the Shell sort is more etticient. 1he Shell sort,
named tor its developer David Shell, uses a value called a gap to compare array elements. As
part ot the Shell sort, the gap is halved using the tormula, {{gap=$gap/2|| to determine
vhich elements to compare. Instead ot alvays comparing tvo adjacent elements as in the
bubble sort, the Shell sort algorithm starts ott comparing tvo elements that are distant
trom one another and ends up comparing tvo adjacent elements by minimizing the gap
interval. DMstant IlInInts are tvo values in the array that are separated by a gap interval
ot more than one. In the Shell sort algorithm, as in the bubble sort, adjacent elements are
separated by a gap interval ot one. So, $al and $a3 vould be considered distant
38 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
ImTlemeRXMRK a SLell SoVX 39
elements vhile $al and $a2 vould be considered adjacent elements. Consider the
pseudocode tor the Shell sort algorithm
lhe ap is initiaii:eo to haif the num|er of eiements.
;hiie ap >=1
(o
ntii no more suaps exist for the .urrent ap
(o
Compare ^ ano (^ ap) oata eiements.
If ^ > (^ ap) lhen
:uap ^ ano (^ ap).
:et :uappeo :aria|ie to "Y."
Lnoif
(one
ap is hai:eo.
(one
1he Shell sort has three loops.1he goal ot the Shell sort is to close the gapon unsorted
items, in this case, N and {N + Gap|. Once this is done, the array is sorted. ligure 9-4
shovs the Shell sort script.
Iike the bubble sort, the Shell sort uses the outer loop to control the number ot array passes.
Once the gap is zero, this loop terminates. In Ioop 2, the until $Swapped = N
statement tests it a svap has occurred on this pass. 1he term pass applies to the Shell
sort as it does in the bubble sort. It there is nothing to svap because the most distant
elements are sorted tor this pass, then gap is halved again. It there is something to svap,
it uses the current gap because distant elements are unsorted tor this pass. As the gap
reaches zero, the elements tested tor svapping are closer together.
9
1he inner loop for {{ i = 0, i <= {{$Last~$gap||, i++ ||, controls the
number ot iterations in each pass. Inside this loop is the decision statement,
if ${a$i} > ${a`expr $i + $gap`} , vhich is used to compare items,
i and i plus gap. It is similar to the decision statement used in the bubble sort but
ditters in that it compares elements separateo by the gap. It elements are unsorted, the items
are svapped, and the variable named Svapped is set to Y, indicating a svap occurred.
Both sorts use the same svap tunction. On the very last pass, the Shell sort tunctions like
the bubble sort because adjacent items are being tested.
ligure 9-3 shovs the Shell sort algorithm sorting the letters ot the alphabet.1hese letters
are in the same unsorted order as they are in the bubble sort in ligure 9-3. Notice that
the number ot passes tor the Shell sort is only tour. Pecall that it took 23 passes to
accomplish the sort in the bubble sort shovn in ligure 9-3.
while $gap -ge 1 ]
do
until $Swapped = N ]
do
Swapped=N
for {{ i = 0, i <= {{$Last-$gap}}, i++ }}
do
if ${a$i]} \> ${a`expr $i + $gap`]} ]
then
swap $i `expr $i + $gap`
Swapped=Y
fi
done
done
Swapped=Y
done
OuLer loop Koverns Lhe number o passes
LhrouKh Lhe array once Lhe Kap Ms 0, Lhe
scrMpL Ms LermMnaLed
*MKuVe 9- Loops used by Lhe Shell sorL scrMpL
Loop 2 LesLs wheLher or noL a swap has
occurred Mn Lhe Mnner loop M Lhere Ms no
swap, LhMs loop LermMnaLes, and Lhe Kap Ms
halved M Lhere Ms a swap, LhMs loop conLMnues
wMLh Lhe currenL Kap
lnner loop swaps
unsorLed elemenLs,
comparMnK Lhe elemenLs
qMr and qM + Kapr once
a swap occurs, ML seLs Lhe
varMable qSwappedr
Lo qYr
lnner loops conLMnue Lo
process as lonK as qMr Ms
less Lhan Lhe lasL
subscrMpL number less Lhe
Kap, or qlasLr - qKapr
350 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
ImTlemeRXMRK a SLell SoVX 351
Next you vill implement the Shell sort to sort a list ot items.You vill allov the user to
enter the maximum number ot elements to sort. 1hen the user vill enter the elements
in random order. linally, the Shell sort vill be used to sort the items in descending order.
1o MnplInInt thI ShIll sort
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a tile named ShIllSort in your $HOME/bin directory.
3. Insert the tolloving lines ot code to create the tunctions to get the data and
svap the data
GetData{}
{
read -p "Enter the number of elements to sort: " max
for {{items=0, items <= $max-1, items++}}
do
read -p "Enter element number $items: " a$items]
done
}
swap{}
{
local T=${a$1]}
a$1]=${a$2]}
a$2]=$T
}
*MKuVe 9-5 Shell sorL used Lo sorL 26 leLLers o Lhe alphabeL
9
4. Insert the tolloving lines ot code to create the tunction called GetStarted to
initialize necessary variables and display messages
GetStarted{}
{
First=0
echo "The unsorted array"
echo ${a@]}
n=${#a@]}
{{Last=$n - 1}}
{{gap=$Last/2}}
{{swapnum=0}}
Swapped=Y
}
3. Insert the tolloving lines ot code to create the tunction called ShellSort that
pertorms the Shell sort
ShellSort{}
{
while $gap -ge 1 ]
do
until $Swapped = N ]
do
Swapped=N
for {{ i = 0, i <= {{$Last-$gap}}, i++ }}
do
if ${a$i]} < ${a`expr $i + $gap`]} ]]
# Descending order swap
then
swap $i `expr $i + $gap`
Swapped=Y
fi
done
done
Swapped=Y
{{gap=$gap/2}}
done
}
6. Insert the tolloving lines ot code tor the main section ot the script that calls
the tunctions and displays the sorted array
# Main section of the script
GetData
GetStarted
ShellSort
echo "The sorted array"
echo ${a@]} # Display the sorted array.
7. Save the script, and then close the editor.
352 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
ComTaVMRK XLe &ubble SoVX aRH SLell SoVX 353
8. Make the script executable, and then execute the script. Lnter 4 tor the num-
ber ot elements to sort, and then press LntIr. Next, enter these elements
hannIr, vrInch, NMgsav, and toolkMt. Be sure to press Lnter atter you enter
each item. See ligure 9-6. 1he items are shovn in both unsorted order and in
descending sort order.
9. Pun the script again. Lnter tor the number ot elements to sort, and then
press LntIr. Next, enter these elements 1, 2, 3, 4, , and . Be sure to press
Lnter atter you enter each number. See ligure 9-6. 1he items are shovn in
both unsorted order and in descending sort order.
10. Close your vindov, and then log out.
'OM4A6IN+ 8H) &U&&L) 7O68 AND 7H)LL 7O68
Lven though the Shell sort only took tour passes to sort the 26 letters in ligure 9-6, tor
a smaller number ot elements in an array the bubble sort pertorms a smaller number ot
comparisons than the Shell sort.1his is because tor a small unsorted array, it is more etticient
to compare every adjacent item, as done by the bubble sort, than to compare distant
items (and ultimately adjacent,, as done by the Shell sort.
Although small is a relative number, in this case, small is typically under 23 unsorted
elements. Iook at a moditication ot the tvo previous scripts vith an added variable that
displays the number ot actual comparisons pertormed inside the decision statement ot
each algorithm.1his variable is used because a comparison, done vith the if statement, is
*MKuVe 9-6 OuLpuL o Lhe Shell sorL used Lo sorL MLems Mn descendMnK order
SLep 8: our iLems LhaL are
inpuL and Lhe resulLin sorL
SLep 9: six iLems LhaL are
inpuL and Lhe resulLin sorL
9
a processor intensive activity and translates to more time needed tor each sorting algorithm.
By comparing these tvo elements you can see hov much vork each algorithm must
pertorm.
Iook at ligure 9-7 and notice that tor an unsorted array containing seven elements
zucchini, pear, orange, banana, carrot, peach, and applethat the bubble sort only pertorms
21 comparisons vhile the Shell sort pertorms 30. In this case, the bubble sort is more
etticient.
Nov, it you look at ligure 9-8, you notice that the bubble sort pertorms 323 comparisons
tor 26 unsorted items and the Shell sort pertorms 271 comparisons tor the same 26 unsorted
items. Here, the Shell sort is more etticient.
*MKuVe 9-7 ComparMson o Lhe bubble sorL and Shell sorL or a small number o unsorLed
elemenLs
35 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
ImTlemeRXMRK SequeRXMal SeaVcL 8ecLRMques 355
1he bubble sort compares adjacent items, vhether sorted or not, on every pass and it alvays
makes N - 1passes.1he Shell sort starts out comparing distant items tirst until it tinally com-
pares adjacent valuesit does not alvays compare adjacent items as the bubble sort does.
1able 9-1 shovs a summary ot the number ot comparisons ot running both sorting
algorithms vith varying amounts ot data on the same computer.
AmouRX of DaXa )lemeRXs 8Le SLell SoVX 8Le &ubble SoVX
5 17 10
7 30 21
26 271 325
58 960 1,653
106 2,462 5,565
208 7,708 21,528
8able 9-1 Number o comparMsons or dMerenL MnpuL or Lhe Shell sorL and Lhe bubble sorL
*MKuVe 9-8 ComparMson o Lhe bubble sorL and Shell sorL or a larKer number o unsorLed
elemenLs
9
What you should understand atter looking at the table is that each sorting algorithm can
be more or less advantageous depending upon the amount ot data you vant to sort.
-M4L)M)N8IN+ 7)QU)N8IAL 7)A6CH 8)CHNIQU)S
1here may be times vhen you need to search tor data in an array.You can employ tvo
ditterent search techniquessequential search or binary searchvhen you vant to tind
one piece ot data in a small or large array.
1he simplest search you can pertorm in an array is the sequential search.1he sIquIntMal
sIarch starts vith the tirst array element and increments the subscript until the data item
you are searching tor is tound or there are no more data elements in the array. It the item
is tound, it is displayed. It the item is not tound, then a message is displayed indicating the
item vas not tound. 1he logic ot the sequential search script is straighttorvard. 1he
sequential search does not require its data to be sorted in primary key tield order because it
inspects each array element anyvay. Consider the pseudocode logic ot the sequential search
:et Iouno :aria|ie to ^.
Peao I( to sear.h.
:et the arra's su|s.ript to 0.
;hiie arra items exist
(o
Compare item in arra to item sear.hin for.
If there is a mat.h
(ispia the re.oro.
:et Iouno to "Y".
Preak out of the ioop.
Lnoif
In.rement su|s.ript | 1.
(one
If not founo
(ispia "^ot Iouno" Messae.
Lnoif
Next you vill implement a sequential search to search tor one ot tive animal records in
an array. Lach animal record is composed ot an ID and the animal name and is stored
in the array, using a colon as a delimiter.
356 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
ImTlemeRXMRK &MRaVy SeaVcL 8ecLRMques 357
1o crIatI thI sIquIntMal sIarch
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a tile named AnMnalSIarch in your $HOME/bin directory.
3. Insert the tolloving lines ot code to create the array or records, read in the
ID number to search, and set tvo variables. Note the variable n equals the
maximum number ot elements in the array.
a={ 1:"King Pup" 2:"Fritz" 3:"Princess" 4:"Molly Cat"
5:"Ginger" }
read -p "Enter animal identification number: " tid
n=${#a@]}
Found="N"
4. Insert the tolloving lines ot code to initiate the search loop
for {{ count=0, $count <=n , count++ }}
do
3. Insert the tolloving lines ot code to cut the id tield trom the record and to
compare the ID that is read in vith the id in the array
id=`echo ${acount]} [ cut -d: -f1`
if $tid = $id ]]
then
6. Insert the tolloving lines ot code to display the matched record, set lound to
Y, and break out ot the loop read
echo ${acount]}
Found="Y"
break
7. Insert the tolloving lines ot code to terminate the decision statement and loop
fi
done
8. Insert the tolloving lines ot code to test the lound variable. It lound is never
set to Y, then the record vas not tound and an appropriate message should
be displayed
if $Found = "N" ]
then
echo "Animal record not found!"
fi
9. Save the script, quit the editor, make the script executable, and then execute
the script.
10. Lnter 1 vhen prompted tor input, and then press LntIr. See ligure 9-9. 1he
record tor King Pup is displayed.
9
11. Lxecute the script again, enter 3 vhen prompted tor the animal identitication
number, and then press LntIr. See ligure 9-9. 1he record tor Princess is
displayed.
12. Lxecute the script again, enter vhen prompted tor the animal identitication
number, and then press LntIr. See ligure 9-9. 1he record tor Ginger is
displayed.
13. Lxecute the script again, and then enter 9 vhen prompted tor the animal
identitication number. See ligure 9-9. A message is displayed indicating that
the record vas not tound.
14. Close your vindov, and then log out.
-M4L)M)N8IN+ &INA6Y 7)A6CH 8)CHNIQU)S
A sequential search is tine tor small amounts ot data, but it is not very etticient tor large
amounts because each element in the array is compared. 1here is a much taster search
algorithmthe binary search algorithm. One major ditterence betveen the sequential
search and the binary search is that the binary search requires its data to be sorted betore
searching. 1he binary search uses a divide and conquer method to locate a data item
much more quickly than the sequential search. 1he expression, divide and conquer in
this case means that the script divides the data into more manageable pieces in order to
conquer the problem ot searching tor an item. Assume you have over 3,000 data items
and you vant to search tor just one. It it just so happens that you needed to tind item
number 3,000 out ot all 3,000 data items, tinding it vould take quite some time using
*MKuVe 9-9 Search resulLs or Lhe AnMmalSearch scrMpL
SLep 11: inpuL o 3 and
search resulL o Princess
SLep 13: inpuL o 9 resulLs
in record noL ound
messae
SLep 10: inpuL o 1 and
search resulL o Kin Pup
SLep 12: inpuL o 5 and
search resulL o Giner
358 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
ImTlemeRXMRK &MRaVy SeaVcL 8ecLRMques 359
the sequential search method.1he binary search vorks by continually dividing the array
into sections. 1hen the value you seek is compared to an element in the array.
1he binary search uses a variable named Middle to locate the item tor vhich you are
searching. It the element located at Middle is equal to the value you seek, then you`ve tound
your item, and the search completes. It the item you seek is less than the element, then the
array is divided, and the top halt ot it is searched. It the item you seek is greater than the
element, then the bottom halt ot the array is searched. 1he binary search continually
searches tor the element by pertorming successive cuts until the item is tound. It the item
is never tound, it is a good idea to have a message displayed in your script indicating this.
NMddle
= 3
0 A
1 8
2 C
3 D
4 L
5 F
6 G
7 H
8 l
9 J
SubscrMpL lLem
NMddle
= 2
0 A
1 8
2 C
3
4 L
5 F
6 G
7 H
8 l
9 J
SubscrMpL lLem
NMddle
= 1
0 A
1 8
2 C
3
4 L
5 F
6 G
7 H
8 l
9 J
SubscrMpL lLem
NMddle
= 4
0 A
1 8
2 C
3
4 L
5 F
6 G
7 H
8 l
9 J
SubscrMpL lLem
1hMs Ms Pass 3 1he varMable
NMddle now equals Lhe MnLeKer 2
Here NMddle = (2 + 3) / 2
whMch Ms Lhe MnLeKer 2
1hMs Ms Pass 2 1he varMable NMddle
now equals Lhe mMddle subscrMpL o
Lhe Lop shaded hal ALer Lhe second
pass, Lhree-quarLers o Lhe MLems are
elMmMnaLed NMddle = (0 + 3) / 2 whMch
Ms Lhe MnLeKer 1
1hMs Ms Pass 1 and Lhe MLem Lo be searched Ms qDr 1he
varMable NMddle equals Lhe mMddle subscrMpL Mn Lhe
array On Lhe MrsL pass, one-hal o Lhe MLems are
elMmMnaLed 8ecause MLem qDr Ms Mn Lhe Lop hal o Lhe
array, search Lhe Lop hal NMddle = (0 + 9) / 2 whMch
Ms Lhe MnLeKer 4 Remember Lhe shell works wMLh
MnLeKers only
1hMs Ms Pass 4 1he varMable NMddle now
equals Lhe mMddle subscrMpL, whMch
happens Lo conLaMn Lhe value you are
seekMnK, qDr NMddle = (3 + 3) / 2
whMch Ms Lhe MnLeKer 3
D
D
D
*MKuVe 9-10 9ndersLandMnK Lhe bMnary search
9
1ake a look at an example that can help you understand hov the binary search vorks.
Say you have an array ot sorted letters as shovn in ligure 9-10 and you vant to search
tor letter D in the array. In the tigure, you can see hov the array is halved each time
the item that you are seeking, in this case D, is not equal to the variable named Middle.
In Pass 1, the Middle variable equals the middle subscript in the array, vhich in this case
is 4. During the tirst pass, one halt ot the items are eliminated.
1he items are eliminated using a decision statement.1he if statement is used to compare
items in the array. It the item you are seeking is equal to the item tor subscript Middle,
then a match has occurred and the binary search terminates. It the item tor subscript
Middle is less than the item you are seeking, the top halt ot the array is searched. 1he
bottom halt is not searched because the items are sorted and compared. It the item tor
subscript Middle is greater than the item you are seeking, the bottom halt ot the array
is searched. In this case, the top halt is not searched because the items are sorted and
compared.1his is repeated until either the item you seek matches the item tor subscript
Middle or the record is not tound.
Because item D is in the top halt ot the array, the top halt is searched instead ot the lover
halt. In Pass 2, the Middle variable nov equals the middle subscript ot the top shaded halt.
By the end ot this pass, three-quarters ot the items are eliminated trom comparison. In
Pass 3 the Middle variable nov equals 2. Notice the search is closing in on the targeted
item. linally, in Pass 4 the Middle variable equals the subscript you are seeking.
JusL remember, Lhe binary search divides Lhe array inLo Lwo ("bi" in Lhe Lerm
binary) on each pass. 8ecause iL works by comparin iLems, Lhe binary search
requires Lhe daLa Lo be sorLed.
Next you vill implement a binary search to locate an employee record tor George
Patel`s Computer Shop. A record contains tvo tieldsLmployee Name and the Shitt
(e.g., 1, 2, or 3, they vorkseparated by a colon.You vill search using Lmployee Name
as the primary key tield. 1he goal is to locate the shitt the employee vorks using the
Lmployee Name.
1o crIatI a bMnar] sIarch to locatI a fMIld vMthMn a rIcord
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a tile named ShMftSIarch in your $HOME/bin directory.
3. Insert the tolloving line ot code to create the array that holds the employee
records
emp={ Adam:3 Bob:1 Carlon:2 Dijon:2 Eve:1 Fritz:2 Gunter:3 }
4. Insert the tolloving lines ot code to read in the name to search
read -p "Enter name to search: " TempName
8MT
360 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
URHeVsXaRHMRK XLe HeVe DocumeRX 361
3. Insert the tolloving lines ot code to set up the initial variables
First=0
n=${#emp*]}
{{Last=$n - 1}}
Found="N"
6. Insert the tolloving lines ot code to begin the loop tor the binary search
while $First -le $Last ]
do
7. Insert the tolloving lines ot code to calculate the variable Middle
{{Middle={$First + $Last} / 2}}
8. Insert the tolloving lines ot code to cut the record into tields
Name=`echo ${emp$Middle]} [ cut -d: -f1`
Shift=`echo ${emp$Middle]} [ cut -d: -f2`
9. Insert the tolloving lines ot code to test tor a match
if $TempName = $Name ]]
then
echo "Employee $Name works Shift $Shift "
Found="Y"
break
fi
10. Insert the tolloving lines ot code to set Middle so the top halt ot the array is
searched on the next iteration
if $Name > $TempName ]] # Set up for searching top half
on next iteration.
then
{{Last=$Middle - 1}}
fi
11. Insert the tolloving lines ot code to set Middle so the bottom halt ot the
array is searched on the next iteration
if $Name < $TempName ]] # Set up for searching bottom
half on next iteration.
then
{{First=$Middle + 1}}
fi
done
12. Insert the tolloving lines ot code to display a message it there is no match
if $Found != "Y" ]
then
echo "Record not found"
fi
9
13. Save the script, quit the editor, make the script executable, execute the
script, enter Adan vhen prompted tor the name, and then press LntIr. See
ligure 9-11. Notice that the search returns the shitt as number 3.
14. Lxecute the script again, and then enter LvI vhen prompted tor the name.
See ligure 9-11. Here the search returns the shitt vorked as number 1.
13. Lxecute the script again, and then enter Carlon vhen prompted tor the
name. See ligure 9-11. Notice that the search returns 2 as the shitt he vorks.
16. Lxecute the script again, and then enter LMn vhen prompted tor the name.
See ligure 9-11. Notice the message Pecord not tound is returned because
Iin doesn`t exist in the array.
17. Close your vindov, and then log out.
9ND)6S8ANDIN+ 8H) ,)6) (OCUM)N8
A here document is not really a document tile at all. It is simply used to signity the
beginning and ending ot commands or text that can be collectively used in a command. A
hIrI docunInt allovs you to enter text on multiple lines to be used as input into a
program. 1he benetit ot using a here document is that it is etticient.You do not need an
editor such as vi as you do vhen you create a regular tile, and the here document is
temporarily stored in memory vhen the script containing it executes. So, access to it is
taster than dealing vith a tile on disk. You use the here document vhen you vant to
enter a small amount ot data at the command line to be processed by a program but do
*MKuVe 9-11 Search resulLs o Lhe ShMLSearch scrMpL
SLep 13: Adam search
shows ShiL 3 as resulL
SLep 16: Lin search resulLs
in "Record noL ound"
messae
SLep 14: Lve search shows
ShiL 1 as resulL
SLep 15: Carlon search
shows ShiL 2 as resulL
362 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
URHeVsXaRHMRK XLe HeVe DocumeRX 363
not vant to use an editor. You vould typically use this vith the cat, mail, or sort
commands to read a body ot text at the command line. 1he tormat ot a here document
is as tollovs
command << here~document~name
Text 11ne 1
Text 11ne 2
Text 11ne 2
...
here~document~name
Note that the command can be any Iinux command that allovs you to redirect input.
1he tvo less-than symbols are required and are used to redirect the text lines into the
Command.You cannot use a single less-than symbol because it is used to redirect input
trom an actual tile.1he text lines are delimited by the name ot the here document, specitied
in the above code as here~document~name. 1he tirst occurrence ot the document
name marks the beginning ot the here document.1he second and last occurrence ot the
document name on a line by itselt identities the end ot the here documentit is like
an end-ot-tile (LOl, symbol to a tile. 1he tirst and second document name must be
identical. Note the here~document~name is user-detined. Also note that a right arrov
symbol, >, appears atter you enter the tirst line and disappears atter you terminate the
here document. 1his is the prompt tor the here document.
Iook at an example. In the tolloving code, the cat command is used to help you
understand hov to implement a here document.
cat << Here
Today is `date`.
The stock price of the company rose 4 points yesterday.
Have a wonderful day!
Here
In this example, the tirst line, cat << Here, indicates to the shell that the cat command
is using a here document as input. 1he next three lines are the actual data or text ot the
here document. 1he tinal line, Here, terminates the here document.
A here documenL eLs iL name because Lhe daLa is liLerally "here" on Lhe
command line or Lhe proram usin iL-insLead o wiLhin an acLual ile.
Next you vill create a here document.
1o crIatI a scrMpt that usIs a hIrI docunInt
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Insert the tolloving lines ot code to create a here document that you can e-mail
to yourselt. Be sure to replace username vith your ovn username.
8MT
9
mail YWIVREQI << MailDoc
Today is `date`.
A meeting will be held in room B11 at 2 pm.
It will cover the production reports for last week.
Please be prompt.
Thanks,
MailDoc
3. Wait a tev minutes tor the mail daemon to send the mail.
4. 1ype mail to receive your e-mail, and then press LntIr. A list ot e-mail messages
appears vith message numbers to the lett ot each line in the list.
3. 1ype RYQFIV vhere num|er is one ot the numbers in the e-mail message list,
and then press LntIr.
6. Pepeat Step 3 until you see the contents ot the here document you created
in Step 2.
7. Close your vindov, and then log out.
9ND)6S8ANDIN+ *IL) %CC)SS
In this section, you vill learn hov to process records vithin tiles. FMlI accIss is the act
ot accessing records vithin tiles that are stored on disk. 1here are tvo components to
tile accessreading records and vriting records. Lsing tiles allovs you to read and vrite
records to and trom a tile on disk, vhich is a permanent computer storage medium.
Lntil nov in this book, most ot the data you have been dealing vith has not been stored
permanently.You need to knov hov to access records in tiles because almost all orga-
nizations today process data that is either saved to or retrieved trom disk.
1o process records vithin tiles, you need to use the redirection symbols and tile descriptors
you learned about in Chapter 4. Although tile descriptor 0 is reserved tor standard input,
tile descriptor 1 is reserved tor standard output, and tile descriptor 2 is reserved tor standard
error, you can use other tile descriptor numbers to reter to tiles that you create.1o success-
tully access tiles you need to understand hov to open tiles, process data vithin them,
and close those tiles.
OTeRMRK XLe *Mle
1o access data vithin a tile, you need to be able to open the tile. Here is the general
torm tor opening a tile
f11e~descr1tor < f11ename
Where f11e~descr1tor is a number betveen 0 and 9 representing the tile descriptor.
You must use a tile descriptor because the shell uses the tile descriptor to reter to the
tile. 1he shell does not allov you to substitute a tilename tor the tile descriptor. You
should use numbers 3 though 9 vhen accessing your ovn tiles because 0, 1, and 2 are
already reserved. It is up to you to decide vhich tile descriptor number to use. 1he
36 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
URHeVsXaRHMRK *Mle Access 365
f11ename is simply a user-detined tilename. Consider the tolloving example
3< in.dat. lile descriptor 3 is used to reter to a tile named in.dat.
Remember, you reer Lo Lhe ilename in.daL by iLs ile descripLor insLead o Lhe
ilename wiLh Lhe scripL.
4Vocess XLe DaXa-6eaHMRK 6ecoVHs fVom a *Mle
Once the tile is open, you can read and process the records vithin it. Note a record here
is considered to be one line ot text. Peading a record involves placing the record in a
variable tor later processing. Once you have the record in the variable you can use the cut
command to split the record into tields. Processing includes tasks such as displaying tields,
totaling tields, counting the number ot records or pertorming decision logic on tields. Here
is the general tormat tor reading a record vithin a tile atter it has been opened.
read var1ao1e~name <& f11e~descr1tor
1his is vhere var1ao1e~name equals the contents ot a line ot text vithin the tile.1he
read statement is used and is moditied to read one line ot the tile into the variable.1he
symbols, <&, are required.Again, f11e~descr1tor is the number representing the tile.
Consider the tolloving example read InRecord <&3.1he variable, InPecord, contains
a record. Notice the tile descriptor, 3, is used in the opening ot the tile. Pemember, tile
descriptor 3 reters to the tile named in.dat. So, in this example, you are reading the tirst
line ot the in.dat tile into the variable named InPecord vhich can nov be cut into tields
or manipulated using other programming logic.
Pecords are processed sequentially trom the beginning ot a tile. Lach record must be
read using the read statement.
4Vocess XLe DaXa-WVMXMRK 6ecoVHs Xo a *Mle
Pecords must tirst be vritten to a tile in order to be read later. 1o vrite a record to a
tile using the shell, you use the echo statement to redirect the tields to a tile. Here is
the general tormat
echo ${var1}:${var2}:${var2}... >> f11ename
1his is vhere var1, var2, and var2 are variables to be vritten to a tile named f11ename.
1he output is redirected using the redirect append operator, >>, because using just the
redirect operator, >, vould overvrite existing records in the tile.
Iook at an example. ack McAllister vorks as a shoe salesman. 1he company he vorks
tor requires him to enter sales tor the veek into a shell script.1he tields tor a shoe record
are Model, Manutacturer, Price, and Quantity Sold. Here is the actual code
8MT
9
read ~p "Enter Model: " Model
read ~p "Enter Manufacturer: " Mfg
read ~p "Enter Price: " Price
read ~p "Enter Quantity Sold: " Qty
echo ${Model}:${Mfg}:${Price}:${Qty} >> shoe.dat # Write
the record to the file named shoe.dat.
Notice the last statement lists each tield separated by a colon, and then redirects the tields
to a tile called shoe.dat. Atter the data is vritten to a tile, the cut command can be used
to access each tield.
ligure 9-12 shovs the above code tor vriting records as part ot the Shoe1 script. In the
tigure, the Shoe1 script`s contents are displayed. Within Shoe1, you can see that tour
variables can be entered trom the keyboard, and then the variables are redirected to the
shoe.dat tile. Next, notice the execution ot the script vith the data tor the Sneaker and
Dress Shoe entered. linally, you can see the contents ot the shoe.dat tile that are created.
1he last line ot the script creates this tile by redirecting the tour tields as a record to it.
ClosMRK XLe *Mle
Once you are tinished processing the records vithin a tile, the tile needs to be closed. It
is good programming practice to close your tiles to avoid the chance ot corruption by
other programs. Here is the general torm
f11e~descr1tor <&~
1o close the tile named in.dat that vas opened and processed previously, you simply
enter the code, 3<&~.
*MKuVe 9-12 WrMLMnK records Lo Lhe shoedaL Mle
ConLenLs o Shoe1 scripL
1wo sample execuLions
ConLenLs o shoe.daL ile
aLer execuLions
366 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
URHeVsXaRHMRK *Mle Access 367
CombMRMRK OTeRMRK, 4VocessMRK, aRH ClosMRK a *Mle MR a ScVMTX
Nov that you`ve seen hov to open, process, and close a tile, next you vill put these steps
in a script to process data. 1his is best done vith the tolloving exercise, in vhich you
vill process records vithin tiles. lirst, you vill create three records in a tile, then you
vill create a script that vill process the three records vithin the tile, and tinally, you vill
close the tile.
1o procIss thrII rIcords vMthMn a fMlI
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a tile named Mndat in your $HOME/bin directory. 1his is the data tile.
3. Insert the tolloving lines ot code to create the three records, one per line.
Note that the tirst tield is the ID number, the next is the employee name, and
the last is the salary.
1:Li Tang:50000
2:Mary Jones:64033
3:Greg Haywood:56444
4. Create a script named ProcIssRIcsA in your $HOME/bin directory.
3. Insert the tolloving lines ot code to open the tile using the tile descriptor, 3,
read and display all the records into the script, and then close the tile
3<in.dat
read Record <&3
echo $Record
read Record <&3
echo $Record
read Record <&3
echo $Record
3<&-
6. Save the script, close the editor, make the script executable, and then execute
the script. 1he data vithin the tile is displayed on the screen.
7. Close your vindov, and then log out.
UsMRK LooTs Xo 6eaH MR DaXa
In the previous exercise, you have one read statement tor each record.What vould you
do it more records than you thought existed in the tile In that case, any records atter
the third vould not be processed. Normally, tiles have an undetermined number ot
records, so it is likely that you vould not knov hov many read statements to use. 1he
best approach is to use a looping structure to read and process the records in the tile.
Lsing a loop, such as while or until, allovs you to process any number ot records
vithin the tile vithout specitically coding tor a specitic number. In the tolloving code,
the tile opens and vhile there are records to be read, they are, and their contents are dis-
played. Once there are no additional records, the tile closes.
9
3< in.dat # Open the file.
while read Record <&3 # While there are records, read them.
do
echo $Record # Display the record.
done
3<&~ # Close the file.
Another approach that accomplishes the same goal is demonstrated in the next script.
1his script uses a shortened version ot the previous script by opening and closing the
tile in one statement. While you can achieve the same results vith either this script or
the previous one, it is important to understand alternative approaches provided by the
shell.You may come across this technique in system shell scripts. 1his technique is sim-
pler because you don`t have to explicitly reter to tile descriptors.
while read Record
do
echo $Record
done < in.dat # Open and close the file in one step.
Next you vill use the shortened approach vith the until statement to read through
the records in the tile.You are using the until statement instead ot the while statement
to gain greater tamiliarity vith the ditterent loops available tor tile access.You vill also
display a count ot the total number ot records vithin the tile.
1o usI a loop to procIss an undItIrnMnId nunbIr of rIcords vMthMn a fMlI
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Append the tolloving records to the data tile named Mndat located in your
$HOME/bin directory
4:Francis Martel:50440
5:Gennady Vladosky:45101
3. Create a script named ProcIssRIcsB in your $HOME/bin directory.
4. Insert the tolloving lines ot code to read the records until there are no more
records to be read, close the tile, and then display the number ot records that
are read
until ! read Record # Until there are no morerecords,
read a record.
do
echo $Record
{{RecordCount++}} # Count up the total number.
done < in.dat
echo "The number of records is:" $RecordCount
3. Save the script, close the editor, make the script executable, and then execute
the script. See ligure 9-13. Notice that the tive records are displayed on the
screen tolloved by the total number ot records.
6. Close your vindov, and then log out.
368 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
ValMHaXe DaXa 369
9
:ALIDA8) (A8A
It is important to validate your data betore it is ever vritten to the screen or tile. 1here
is an expression in the computer industry Garbage In Garbage Out. It you don`t vali-
date your data, it may vrite invalid data to a tile. Invalid data is garbage. It you allov
garbage data to go in, you can reasonably expect garbage to come out ot your program,
hence GarbagI In GarbagI Out (GIGO). Lltimately, invalid data could be printed
on a sales report or an incorrect grade could be printed on a student`s transcript. So, to
prevent GIGO, you should validate your data. Generally, users don`t consciously put
invalid data into tields. lor the most part, it is an honest mistake. lor example, acciden-
tally placing a character in a tield that is supposed to be numeric happens trequently. Can
you imagine hov you vould teel it your paycheck vas not processed because someone
entered AA instead ot 43 in the hours tield tor the number ot hours you vorked
1here are several data validation techniques you can use to help remove the probability
ot invalid data.1hese can be implemented using shell script techniques and can be placed
in a tunction library tor all scripts to use. 1he techniques are listed belov
Lmpty
Iength
Numeric
Pange
*MKuVe 9-13 9sMnK a loop Lo process Mles
SLep 5: ive records are
displayed as resulL o
execuLion
8esXMRK foV aR )mTXy VaVMable
Many times a user may not enter anything and simply press the Lnter key on a tield by
mistake. 1hey may be caught up in the business ot the day and accidentally leave a tield
empty. In order to test tor this, you can use a decision construct. ligure 9-14 shovs the
code to determine it a variable is empty or not.
In the tigure, the contents ot a variable named ans are tested tor an empty value. It ans
is empty, a message is displayed that it is empty, othervise, the contents ot the variable
are displayed.
Next you vill create a tunction that tests vhether a variable is empty.1he benetit ot setting
this up as a tunction is that you can place the code in a tunction library, and then call
the tunction trom the shell or trom vithin a script.
1o crIatI a functMon that allovs ]ou to tIst for an Inpt] varMablI
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a tile named Lnpt]1Ist in your $HOME/bin directory.
3. Insert the tolloving lines ot code to create the tunction named empty
empty{}
{
if $1 = "" ]]
then
return 1 # If the parameter is empty, then return 1.
else
return 0 # If the parameter is not empty, then return 0.
fi
}
4. Insert the tolloving lines ot code to get the data trom the keyboard, place it in
the variable named ans, and call the tunction vith the contents ot the variable
named ans
read -p "Enter value: " ans
empty $ans
read ans
if $ans = "" # Is the variable empty?
then
echo "variable is Empty"
else
echo $ans
fi
*MKuVe 9-1 1esLMnK or an empLy varMable
370 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
ValMHaXe DaXa 371
3. Insert the tolloving lines ot code to determine vhether the tunction
returned a 1 (empty, or 0 (not empty,
if $? -eg 1 ]] # Check the return value of the
function, either 0 or 1.
then
echo "Field is empty."
else
echo "Field is not empty."
fi
6. Save the script, close the editor, make the script executable, execute the
script, vhen prompted, type , and then press LntIr. A message indicating
the tield is not empty is displayed.
7. Pun the script again, vhen prompted, type abc123, and then press LntIr. A
message indicating the tield is not empty is displayed.
8. Pun the script one tinal time, and then press LntIr. A message indicating the
tield is empty is displayed.
9. Close your vindov, and then log out.
8esXMRK foV LeRKXL
Many times you may need to make sure that a minimum number ot characters are
entered into a tield. lor example, you knov that a Social Security number (SSN, is
exactly nine digits. So, you may vant to test to ensure that a user enters nine digits. 1o
do this, you use ${#var} to test tor a specitic length. In this case, var is the variable name.
1ake a look at an example ot testing to ensure that the SSN ot an employee is nine digits.
1he tolloving code displays a message it the SSN is not exactly nine digits.
read ~p "Enter: " SSN
len=`echo ${#SSN}`
if $len != 9
then
echo "SSN length is not 9 digits"
else
echo $SSN
fi
Next you vill create a script vith a length test tunction. In this tunction, you vill make
sure the tvo-digit state code tor a state is in tact only tvo digits. lor example, the tvo-digit
state code tor Georgia is GA and the tvo-digit state code tor Massachusetts is MA. Also,
it the state code is exactly tvo character positions, they vill be translated into uppercase.
1o crIatI a functMon that allovs ]ou to pIrforn a lIngth tIst
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a tile named LIngth1Ist in your $HOME/bin directory.
9
3. Insert the tolloving lines ot code to create the Ien1est tunction
LenTest{}
{
SCLength=`echo ${#SC}` # SC = State Code
if $SCLength = 2 ]]
then
return 0
else
return 1
fi
}
4. Insert the tolloving lines ot code to get the data trom the keyboard, place it
into the variable named SC, and call the tunction vith the contents ot the
variable named SC
read -p "Enter State Code: " SC
LenTest SC
3. Insert the tolloving lines ot code to determine vhether the tunction
returned a 1 (empty, or 0 (not empty,
if $? -eg 1 ]]
then
echo "State code invalid length"
else
6. Insert the tolloving lines ot code to display the contents ot the variable in
uppercase and terminate the decision statement
echo $SC [ tr :lower:] :upper:] # Display in uppercase.
fi
7. Save the script, close the editor, make the script executable, execute the script,
vhen prompted type nc tor North Carolina, and then press LntIr. See
ligure 9-13.1he letters NC tor the state code ot North Carolina are displayed.
8. Pun the script again, vhen prompted type zzz, and then press LntIr. See
ligure 9-13. A message indicating the length is invalid is displayed.
9. Pun the script again, vhen prompted, type GA, and then press LntIr. See
ligure 9-13. 1he letters GA tor the state code ot Georgia are displayed.
10. Close your vindov, and then log out.
372 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
ValMHaXe DaXa 373
9
8esXMRK foV NumeVMc Values
You may also vant to test to ensure that a tield contains only numeric values. lor example,
you may have an amount tield vithin an application. It a user places nonnumeric data
vithin the tield, errors in calculation may result. In order to test tor numeric values, you
could use pattern-matching techniques along vith the grep command. In the script
shovn in ligure 9-16, a for statement checks each position ot a value to determine it
the position is numeric or not. A variable i in the for loop is set to 0, compared to
the length ot the variable called ans, and incremented by one. Lach position ot ans is
then tested and it the position is not a digit, then the script sets the variable named
Numeric to N and breaks out ot the for loop.You break the loop because you have
tound at least one digit to be nonnumeric and that is all that is needed to make the
overall value nonnumeric.
1he key to this script is the statement val=`echo ${ans:$i:l}`.You sav this used
in Chapter 4, vith this statement you can inspect each position ot a variable. By embedding
this statement inside the for loop, each position ot the variable named ans is set to val
tor each ot the loop`s iterations.
Consider the tolloving example to help clarity this concept. It ans equals 41,then the for
loop executes tvice at most, or the length ot the variable. On the tirst iteration,i is set to
zero and ${ans:0:l} is equal to the tirst position ot 41 vhich is 4. It is numeric so
the for loop increments i. Nov i is set to one causing the zero to change to a one.
1his is the middle variable in the statement ${ans:l:l}. So, position 1 ot 41equals 1.
*MKuVe 9-15 1he lenKLh LesL
SLep 8: resulLs in invalid
lenLh
Nov 1 is not numeric, this causes the echo $val ] grep `0~9 > /dev/null
test to tail and return a status ot one. By the vay, the output ot the grep command is
being redirected to devnull because grep is not displayed on the screen. Because you
don`t need the output, only the return status ot grep is needed.
You can seL up Lhe uncLion shown in Lhe previous scripL in a uncLion library
so LhaL iL can be used by mulLiple scripLs.
In ligure 9-17, you can see the output resulting trom several executions ot N1est2, the
script trom ligure 9-16. Notice vhen 43412 is entered, that the script displays a message
indicating it is numeric. Hovever, vhen 43434331 is entered, the script displays a message
indicating the value is not numericthis is due to the 1 in the value. 1he last value,
3600048((,, is a nonnumeric value as vell.
8MT
Numeric="Y"
read ~p "Enter: " ans
len=`echo ${#ans}`
for {{i=0, i<$len, i++|| # Use a loop to inspect each position of the vari~
able named ans.
val=`echo ${ans:$i:1}`
echo $val ] grep `0~9 > /dev/null # Is the first character a digit?
Retval=$? # Save the return value.
if $Retval ~eq 1 # Test Retval {0=numeric, 1=non~numeric|
then
Numeric="N"
break
fi
done
if $Numeric = "Y"
then
echo "value is numeric"
else
echo "value is not numeric"
fi
*MKuVe 9-16 1he scrMpL or LesLMnK numerMc values
37 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
ValMHaXe DaXa 375
6aRKe CLecks
1here may be times vhere you vant to pertorm a test to ensure that a tield is vithin a
proper range ot values. lor example, you need to enter an hourly rate tor an employee.
1he range may be trom s20 to s99 tor the hourly rate.You could entorce a range test
to ensure no values outside this range are entered.1his does not test the accuracy ot the
rate tor an individual that has been enteredno script or program can do thatbut it
validates that the amount is vithin the specitied range. 1he tolloving example script is
named Pange1. 1he user enters name and hourly rate data, it the amount is not vithin
the range ot 20 to 99, then an error message is displayed, othervise, a record is vritten
to the payroll.dat tile.
read ~p "Enter Name: " Name
read ~p "Enter hours: " amt
if $amt ~ge 20 && $amt ~le 99
then
echo ${Name}:${amt} >> payroll.dat
else
echo "The amount is out of range"
fi
ligure 9-18 shovs the execution ot the script named Pange1. Notice in the tigure that
the amount tor both Dexter Hudlen and Marge IaPue are out ot range.1his is because
their hourly amounts are outside ot the range (20 to 99,. 1he last line shovs the contents
ot the payroll.dat tile. Notice that only records tor Mike McMasterston and Mindy Hallstein
appear.1his is because their hourly amounts are vithin the range (20 to 99,.You can see
hov the use ot the if test eliminated the garbage data by not alloving it into the tile.
*MKuVe 9-17 NumerMc LesL and resulLs o execuLMon KMven varMous daLa
9
Next you vill pertorm a range test to validate a grade.
1o crIatI a scrMpt usMng thI rangI tIst
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a tile named RangI1Ist in your $HOME/bin directory.
3. Insert the tolloving lines ot code to create the tunction to test tor data vith
a range ot 0 to 100
RangeCheckIt{}
{
if $1 -ge 0 && $1 -le 100 ]]
then
return 0 # 0=Within range
else
return 1 # 1=Out of range
fi
}
4. Insert the tolloving lines to create a tunction to read data trom the keyboard
ReadVar{}
{
read -p "Enter grade: " Var1
}
*MKuVe 9-18 LxecuLMon o Lhe RanKe1 scrMpL
376 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
ValMHaXe DaXa 377
3. Insert the tolloving lines ot code to call the PeadVar tunction and the
PangeCheckIt tunction vith the contents ot Var1, and set its exit status to
the variable named PetVal
ReadVar
RangeCheckIt Var1
RetVal=$?
6. Insert the tolloving lines ot code to test PetVal. It the return status equals one,
the data is not vithin the range. It it equals zero, the data is vithin the range.
if $RetVal -eg 1 ]]
then
echo "Out of range!"
else
echo $Var1
fi
7. Save the script, close the editor, make the script executable, execute the
script, vhen prompted, type 0, and then press LntIr. See ligure 9-19. 1he
value is displayed because it is vithin range.
8. Pun the script again, vhen prompted type 0, and then press LntIr. See
ligure 9-19. 1he value is displayed because it is vithin range.
9. Pun the script again, vhen prompted type 100, and then press LntIr. See
ligure 9-19. 1he value is displayed because it is vithin range.
10. Pun the script again, vhen prompted type 400, and then press LntIr. See
ligure 9-19. A message indicating the data is out ot range is displayed.
11. Pun the script again, vhen prompted type -1, and then press LntIr. See
ligure 9-19. A message indicating the data is out ot range is displayed.
12. Close your vindov, and then log out.
9
'HA48)6 7UMMA6Y
Both the bubble sort and Shell sort algorithms svap elements that are unsorted in
an array. 1he bubble sort alvays sorts adjacent elements. 1he Shell sort algorithm
begins by sorting distant elements and then tinishes by sorting adjacent elements.
1he Shell sort uses a gap interval to control the distance betveen elements. 1he
bubble sort is more etticient tor 23 or tever unsorted elements, a Shell sort is more
etticient tor more than 23 unsorted elements.
1he sequential search algorithm searches an array trom the tirst to the last element
unless it tinds a match. Once a match is tound, the search stops. It the search reaches
the last element and there is no match, then it is determined that the element is not
in the array. 1he binary search uses a divide and conquer technique to successively
split the array in halt and compare the searched value to an element in the array.
1he binary search is more etticient than the sequential search tor a large amount ot
data because it does not compare each element in the array to the searched value.
Hovever, the data must be sorted betore the binary search can be used.
A here document is text embedded vithin the body ot a script. It is generally used
instead ot an editor vhen the amount ot text is small.
Pecords can be read trom a disk tile or vritten to a disk tile. liles need to be
opened prior to processing the data. Processing involves reading or vriting the
records. liles should be closed vhen they are no longer needed. liles are opened,
processed, and closed vith the same tile descriptor throughout a script.
*MKuVe 9-19 Several runs o Lhe RanKe1esL scrMpL
378 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
6evMew QuesXMoRs 379
Data needs to be validated in order to prevent Garbage In Garbage Out (GIGO,.
1here are a variety ot data validation techniques including empty, length, numeric,
and range.
6)VI)W 5U)S8IONS
1. uses a divide and conquer technique to locate records.
a. Collating sequence
b. Shell sort
c. Sequential search
d. Binary search
2. It you have tever than 10 records to be sorted in descending order, vhich technique
should be used
a. bubble sort
b. Shell sort
c. sequential search
d. binary search
3. It you have more than 100 records to be sorted in descending order, vhich technique
should be used
a. bubble sort
b. Shell sort
c. sequential search
d. collating sequence
4. A(n, is a tormula or process to accomplish a specitic set ot steps.
a. algorithm
b. here document
c. invalid data
d. gap in the Shell sort
3. A should be pertormed to ensure a tield contains data.
a. Shell sort
b. numeric test
c. sequential search
d. blank test
9
6. Prior to processing a record, you should the tile.
a. sequentially search
b. close
c. read the records trom
d. open
7. Atter processing a record, you should the tile.
a. sequentially search
b. close
c. read the records trom
d. use the collating sequence on
8. It you have over 30,000 items to search, vhich technique is most etticient
a. bubble sort
b. Shell sort
c. sequential search
d. binary search
9. A(n, is used tor adding text to a command and uses the <<
operator.
a. bubble sort
b. numeric test
c. algorithm
d. here document
10. A only compares adjacent values.
a. bubble sort
b. collating sequence
c. Shell sort
d. blank test
11. A tield or variable that is empty is considered .
a. collated
b. sorted
c. searched
d. null
12. A compares distant values and then adjacent values.
a. bubble sort
b. numeric test
c. Shell sort
d. blank test
380 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
6evMew QuesXMoRs 381
13. 1he tacilitates character sorting.
a. bubble sort
b. collating sequence
c. algorithm
d. here document
14. Values in out-ot-sort order in the bubble sort are .
a. collated
b. svapped
c. vritten to a tile
d. closed
13. A can be used to ensure a tield contains a specitied number ot
character or numbers.
a. collating sequence
b. svap tunction
c. length test
d. range test
16. A can be used to ensure the contents ot a tield talls vithin a
specitic minimum and maximum number.
a. collating sequence
b. svap tunction
c. length test
d. range test
17. Which ot the tolloving closes tile descriptor 4 tor the tile named inputtile.dat
a. 4 < inputfile.dat
b. 4<&~
c. 4>&~
d. 4 > inputfile.dat
18. Which ot the tolloving opens tile descriptor 4 tor the tile named inputtile.dat
a. 4 < inputfile.dat
b. 4<&~
c. 4>&~
d. 4 > inputfile.dat
9
19. Which ot the tolloving vrites the tields, LmpName, LmpStatus, LmpSalary to the
tile named payroll.dat, in the order shovn and separated by a colon
a. echo ${EmpName}:${EmpSalary},${EmpStatus} < payroll.dat
b. echo ${EmpName},${EmpSalary},${EmpStatus} > payroll.dat
c. echo ${EmpName}:${EmpStatus}:${EmpSalary} >> payroll.dat
d. echo ${EmpSalary}:${EmpStatus}:${EmpName} < payroll.dat
20. What is the result ot the tolloving script
while read SalesRecord
do
echo $SalesRecord
done < sales.dat
a. It tails due to a syntax error.
b. It vrites records to the sales.dat tile.
c. It sorts the records.
d. It reads records in the sales.dat tile.
,ANDSON 46OJ)C8S
4VoNecX 9-1
In this project, you vill create a script that can use a here document.1he read statement
vill be used to accept input. 1he goal ot this project is to help you understand hov to
create a script that can use a here document.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named ProNIct9-1 in the $HOME/bin directory.
3. Add the tolloving lines ot code
for {{c=0, c<=5, c++}}
do
read a
echo $a
done
4. Save the script, close the editor, and then make the script executable.
3. 1ype the tolloving at the command line
$HOME/bin/Project9-1 << Animals
Cat
Dog
Mouse
Parrot
Lion
Animals
,ERHWSR
4VSNIGX
382 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
HaRHs-oR 4VoNecXs 383
6. Pecord the result.
7. Close your vindov, and then log out.
4VoNecX 9-2
In this project, you vill implement the bubble sort as a tunction to help you understand hov
the bubble sort vorks.1his project vill turther your knovledge ot arrays and tunctions.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Copy the BubblISortClothIs script you created earlier in this chapter to a nev
shell script named ProNIct9-2 in the $HOME/bin directory.
3. Convert the bubble sort in the nev script to a tunction, and then call it vithin
the script.
4. Pecord your results.
3. Close your vindov, and then log out.
4VoNecX 9-3
In this project, you vill implement the Shell sort to sort the data in ascending order.You
vill place the Shell sort in a tunction library to be used in the shell or vithin other
scripts.1his project vill reintorce your understanding ot the Shell sort, arrays, and tunctions.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Copy the ShIllSort script trom the earlier exercise to a nev shell script named
ProNIct9-3 in the $HOME/bin directory.
3. Make the necessary code changes to sort the data in ascending order.
4. Place the nev script in a tunction library tile in the $HOME/bin directory named
ProNIct9-3a.
3. Lse the source command to read and execute ProNIct9-3.
6. Make both scripts executable.
7. Lxecute ProNIct9-3a.
8. Pecord the result.
9. Close your vindov, and then log out.
4VoNecX 9-
In this project, you vill implement the bubble sort algorithm to sort elements in
descending order.1he goal ot this project is to help reintorce the concept ot arrays, tunc-
tions, and the logic intrinsic to the bubble sorting algorithm.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named ProNIct9-4 in the $HOME/bin directory.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
9
3. Lse the bubble sort to sort the tolloving items in descending order
JEVQjVERGLjFVSSOjWXVIEQjXVIIjWLVYFjFYWLjPEKSSRjEVGLMTIPEKSjMWPERHj^SS
4. Save the script, quit the editor, make the script executable, and then execute it.
3. Print your script.
6. Close your vindov, and then log out.
4VoNecX 9-5
In this project, you vill test tields betore you vrite them as a record to a tile.You vill
also pertorm a blank data validation test and use a decision statement to determine it the
data is correct betore vriting a record to the tile. A loop vill be used to allov the user
to continue entering records.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named ProNIct9- in the $HOME/bin directory.
3. Create a tunction, named Lnpt]1Ist, to test tor empty variables. Note that 0 is
not empty and 1 is empty.
4. Insert the tolloving lines ot code to create a loop that reads data trom the keyboard,
to call the tunction named Lmpty1est, and then save the return status
YesNo="Y"
while $YesNo = "Y" ]]
do
clear
read -p "Enter Part Number: " PartNo
EmptyTest $PartNo
Ret1=$?
read -p "Enter Part Name: " PartName
EmptyTest $PartName
Ret2=$?
read -p "Enter Part Price: " PartPrice
EmptyTest $PartPrice
Ret3=$?
3. Insert the tolloving lines ot code to test the return status ot each value passed to
Lmtpy1est. It the data is empty, display a message indicating so. It the data is not
empty, vrite it to the parts.dat tile.
if $Ret1 -eg 1 [[ $Ret2 -eg 1 [[ $Ret3 = 1]]
then
echo "Field{s} blank"
echo "Re-enter, record not written"
else
read -p "Correct {Y/N} ?" Correct
Correct=`echo $Correct [ tr :lower:] :upper:]`
if $Correct = "Y" ]]
then
echo ${PartNo}:${PartName}:${PartPrice} >> parts.dat
,ERHWSR
4VSNIGX
38 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
HaRHs-oR 4VoNecXs 385
jjjjjjjjjjjIGLSj6IGSVHj[VMXXIR
jjjIPWI
jjjjjjjjjjjIGLSj2SXj[VMXMRKjVIGSVH
jjjJM
JM
6. Insert the tolloving lines ot code to ask users vhether or not they vant to continue,
change their ansver to uppercase, and terminate the loop
read -p "Continue {Y/N} ?" YesNo
YesNo=`echo $YesNo [ tr :lower:] :upper:]`
done
7. Save the script, and then quit the editor.
8. Make the script executable, and then execute the script using various data.
9. Pecord your results, and it possible, print your script.
10. Close your vindov, and then log out.
4VoNecX 9-6
In this project, you vill read the records entered in Project 9-3. 1he goal ot this project
is to help you understand hov to read records trom a tile using a loop structure.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named ProNIct9- in the $HOME/bin directory.
3. Write the appropriate code to read the records created in Project 9-3 using a
loop structure.
4. Print the script.
3. Save the script, close the editor, make the script executable, execute the script, and
then record the output.
6. Close your vindov, and then log out.
4VoNecX 9-7
In this project, you vill modity the Project9-3 script to include a numeric test tor the
Part Price.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Copy ProNIct9- to ProNIct9-7 in the $HOME/bin directory.
3. Modity the script to include a numeric test tor the Part Price.
4. Print the script.
3. Lxecute the script vith various data, and then record the result.
6. Close your vindov, and then log out.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
9
4VoNecX 9-8
In this project, you vill implement the bubble sort and the binary search in one script.
You vill also implement the bubble sort and binary search as separate tunctions.1he goal
ot this lab is to help you understand hov to implement sorting and searching into a single
script as tunctions.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named ProNIct9-8 in the $HOME/bin directory.
3. Write a script that implements both the bubble sort and binary search as tunctions.
1he array to sort and search contains an employee record that includes an employee
number tolloved by the employee`s name. 1he contents ot the unsorted array are
as tollovs
a={ 9:Joe 5:Mike 8:Marge 2:Sue 7:Chandra 3:Tian 1:Vien
4:Lars 6:Ivan 0:Edward }
4. Allov the user to search tor an employee ID. It the record is tound, display the
employee ID and the employee`s name. Othervise, display a message indicating
the record is not tound.
3. Lxecute the script vith various data, and then record the result.
6. Close the vindov, and then log out.
'AS) 46OJ)C8S
Case 9-1
You have been hired by 1MI to help their payroll department vrite a sorting algorithm
and a searching algorithm in one script. A record consists ot an employee`s name and his
or her salary. 1he company has approximately 22 employees and is expected to add tive
employees each year tor the next three years, based upon projected grovth rates tor their
company.Write the script tor the type ot sorting algorithm and searching algorithm you
suggest. Allov the user to search by entering an employee name, and then display the
salary given the search results. linally, discuss in vriting vhy you suggest this type ot
sorting algorithm and vhy you believe it is best to implement it nov and over the next
three years.Also, discuss the type ot searching algorithm you suggest and vhy they should
implement it nov and over the next three years. Detend your response.
'EWI
4VSNIGX
,ERHWSR
4VSNIGX
386 CLaTXeV 9 AHvaRceH SLell 4VoKVammMRK
Case 4VoNecXs 387
Case 9-2
Pan-Pacitic Vegetable Corporation needs a tev scripts to be created to handle their veg-
etable orders.You have been hired as a consultant to assist. Here are their requirements
1. Create a script tor adding records given the tields belov.You are to ensure the
numeric tields are numeric and the other tield is not empty betore vriting a
record to the veg.dat tile.
Vegetable Product ID
Vegetable Name
Vegetable Quantity
Vegetable Price
2. Create a script tor reading the records trom the tile. In the same script, till an
array vith the records. 1hen, use one ot the searching algorithms to allov a user
to locate a record based on the ID. Once tound, display all tields, othervise, indicate
the record is not in the tile.
3. Pun the script to create the records. Lse these eight records vith the tields in the
order ot Vegetable Product ID,Vegetable Name,Vegetable Price,Vegetable Quantity
4. Pun the script to search and enter various data.
3. Print all scripts.
VeKeXable 4VoHucX ID VeKeXable Name VeKeXable 4VMce VeKeXable QuaRXMXy
401 8roccoli 4 1
402 Asparaus 6 2
403 Kale 2 1
404 Zucchini 3 8
405 PorLobellos 9 2
406 Onions 1 7
407 Peppers 4 5
408 Spinach 2 4
8able 9-2 Pan-PacMMc veKeLables
'EWI
4VSNIGX
9
389
',%48)6

-2'36436%8-2+ %((-8-32%0
8)',2-59)7 %2( 83307
-RXLMWGLETXIV]SY[MPP
9WIXLIEVFMXVEV]TVIGMWMSRGEPGYPEXSVXSTIVJSVQEVMXLQIXMGSTIVEXMSRW
7IEVGLJSVXI\XYWMRKXLIgrep GSQQERH
9RHIVWXERHXLIWXVIEQIHMXSV
9RHIVWXERH sed GSQQERHW
'VIEXI sed WGVMTXW
9RHIVWXERHWMKREPW
-
n thMs chapter, you vMll learn hov to use addMtMonal shell technMques and tools
SpecMtMcally, you vMll learn hov to use the precMsMon calculator to pertorm
arMthmetMc on numbers that contaMn decMmals, as vell as hov to search tor
text vMthMn tMles usMng the KVIT command You vMll learn the WIH command
vhMch provMdes text-processMng capabMlMtMes at the shell command prompt
lMnally, you vMll learn hov to send and catch sMgnals
9SIN+ 8H) %6&I86A6Y 46)CISION 'ALCULA8O6 8O 4)6*O6M
%6I8HM)8IC 34)6A8IONS
As you knov, you can only pertorm integer-based arithmetic using builtin operations tor
the bash shell. 1o pertorm arithmetic operations on numbers containing decimals, you
can use the bc command. One important aspect about the bc command is the ability ot
the user to arbitrarily set the precision ot the calculations that are pertormedhence
the phrase arbitrary precision in its name. 1his is accomplished vith the scale com-
mand vithin bc. It you try to accomplish the same calculations strictly vithin the shell,
you receive an error.
1here are several options available vith the bc command. A tev ot them are listed in
1able 10-1.
1he bc command has its ovn set ot language statements that vork similarly to the ones
you tind in the bash shell. lor example, the bc command has builtin if, for, and
while statements. It also includes mathematical tunctions such as sine, cosine, and square
root. 1hese tools are especially usetul vhen the Iinux operating system is used in an
engineering environment.
1o give you a sense ot the bc command`s capabilities, 1able 10-2 provides you vith some
ot the commands available vith bc. Some ot them you are sure to recognize because a
similar shell command has been covered in an earlier chapter. It you vould like to knov
more about the bc command, you can reter to its man pages.
OTXMoR DescVMTXMoR )xamTle
length ls a uncLion LhaL reLurns Lhe length {pay_rate|
lenLh o a variable
print ls a uncLion LhaL allows you Lo print "Enter value: "
prinL LexL or Lhe conLenLs o a
variable
read {| ls a uncLion LhaL allows you Lo sales=read{|
read daLa rom Lhe keyboard
8able 10-2 A ew o Lhe bc commands
OTXMoR DescVMTXMoR )xamTle
~h 1he help opLion displays Lhe usae or bc when execuLed bc ~h
~l 1he maLh library opLion allows Lhe use o Lhe sLandard maLh library bc ~l
wiLh access Lo addiLional maLhemaLical uncLions such as sine, cosine,
and LanenL
~q 1he quieL opLion does noL display Lhe normal welcome messae bc ~q
~v 1he version opLion ives you version inormaLion bc ~v
8able 10-1 A ew o Lhe bc opLMons
390 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
UsMRK XLe AVbMXVaVy 4VecMsMoR CalculaXoV Xo 4eVfoVm AVMXLmeXMc OTeVaXMoRs 391
Next, you learn hov to vork vith the bc command.You can execute bc commands in
one ot three vays
Interactively
In a script
In a pipeline command
6uRRMRK FG IRXeVacXMvely
Lnderstanding hov to run bc interactively makes learning hov to execute the com-
mands in a script and a pipeline easier. 1he quickest vay to become tamiliar vith the
bc command is through an exercise. Next you vill enter commands to learn hov to
run bc commands ettectively. You vill also examine the arithmetic precision that bc
otters over the bash shell.
1o usI bc MntIractMvIl] and sIt thI prIcMsMon vMth thI scale connand
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
OTXMoR DescVMTXMoR )xamTle
scale Allows you Lo seL Lhe decimal scale=3
precision
s ls a maLhemaLical uncLion LhaL s{3|
allows you Lo perorm Lhe
LrionomeLric sine uncLion on a
variable
c ls a maLhemaLical uncLion LhaL c{1/3|
allows you Lo perorm Lhe
LrionomeLric cosine uncLion
on a variable
sqrt {| ReLurns Lhe square rooL o a sqrt {4|
uncLion
if {express1on| Allows you Lo perorm decisions; if {hours>=40| print
statement1 else noLe Lhe else porLion is opLional "Overtime Pay" else print
statement2 "Regular Pay"
for {express1on1, Allows you Lo perorm loops; for {var1=1, var1 <=5,
express1on2, Lhis ollows a synLax similar Lo var1++| print var1
express1on2| Lhe shell's for sLaLemenL
8able 10-2 A ew o Lhe bc commands (conLMnued)
10
2. 1o use the bc command interactively, type bc at the shell prompt, and then
press LntIr. As you can see, the bc prompt is ditterent trom the shell`s
prompt. See ligure 10-1. 1he prompt is simply a tlashing cursor. Notice
above the tlashing cursor you have a tev lines indicating the version ot bc
and the copyright intormation. 1his is called the velcome message. Lxamine
vhat it looks like so you can be tamiliar vith detault behavior.
3. 1o help you understand the precision ot bc, set the variable x to 13 by
typing x=15, and then press LntIr. 1he prompt returns to the next line.
4. 1o set the variable y to 7, type y=7, and then press LntIr. 1he prompt
returns to the next line.
3. 1o divide x by y, type x/y, and then press LntIr. 1he ansver 2 appears,
and the prompt returns to the next line. Notice that there are no decimal
places in the ansver by detault.
6. 1o arbitrarily change the precision using the scale command and set the
number ot decimal places to tvo, type scale=2, and then press LntIr. 1he
prompt returns to the next line.
7. 1ype x/y again, and then press LntIr. 1he ansver ot 2.14 appears, and the
prompt returns to the next line. See ligure 10-1. Notice that there are tvo
decimal places in the ansver.
8. 1o arbitrarily set the precision to tour decimal places, type the tolloving lines
ot code
scale=4
x/y
See ligure 10-1. Notice the ansver ot 2.1428 is displayed on the screen, and
then the prompt returns to the next line.You can see that the division prob-
lem has been carried out to tour decimal places.
9. Arbitrarily set the precision to 10 decimal places to help you understand its
precision turther. 1ype the tolloving lines ot code
scale=10
x/y
See ligure 10-1. Notice the ansver ot 2.1428371428 is displayed on the
screen, and then the prompt returns to the next line.You can see that the
division problem has been carried out to 10 decimal places.
10. 1o quit, type guit, and then press LntIr.1his statement is required to exit bc.
11. Close your vindov, and then log out.
392 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
UsMRK XLe AVbMXVaVy 4VecMsMoR CalculaXoV Xo 4eVfoVm AVMXLmeXMc OTeVaXMoRs 393
AHHMRK UseV IRTuX wMXL FG
You can use the bc command to prompt a user to enter a value in a variable. 1o do this,
you need to use the read tunction vithin bc. Lsing the read tunction is usetul tor mak-
ing bc tlexible because you can get data tor your script trom the keyboard.1his application
ot bc is similar to the shell`s read command. lor example, to display a prompt that reads a
person`s age trom the keyboard in bc, you enter the tolloving
print "Enter age: " , age=read{|
1he bc command also allovs you to pertorm calculations using the various operations
such as multiply, add, divide, and subtract, as you`ve seen in the shell. You can also use
parentheses to change the order ot operation.You need to understand hov to use these
operations in bc in case you need to use its arbitrary precision capabilities. Next you
vill turn ott the velcome message, prompt the user tor data, and read the data trom the
keyboard to pertorm some mathematical operations.
1o usI bc to pronpt thI usIr for data and pIrforn nathInatMcal opIratMons
on thI data
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. 1o remove the velcome message, type bc -g, and then press LntIr. Pecall
trom 1able 10-1 that ~q is the quiet mode ot bc and nov only the prompt is
displayed.
3. 1o set the decimal precision to tvo decimal positions, enter scale=2.
*MKuVe 10-1 9sMnK Lhe bc command Lo perorm arbMLrary precMsMon
SLep 2: welcome messae
SLep 7: resulL includes Lwo
decimal places in answer
SLep 8: resulL includes
our decimal places in
Lhe answer
SLep 9: resulL includes
10 decimal places in
Lhe answer
10
4. 1o read a variable trom the keyboard, type print "Enter value: " ,
val1=read{}, and then press LntIr. See ligure 10-2. 1he prompt Lnter
value appears on the screen. Note that the semicolon is required to separate
the text trom the variable statement.
3. 1ype 50, and then press LntIr.
6. 1o read another variable trom the keyboard, type print "Enter value: ",
val2=read{}, and then press LntIr. See ligure 10-2. 1he prompt Lnter
value appears on the screen.
7. 1ype 6.67, and then press LntIr.
8. 1o add the tvo values, type print "Sum is " , val1 + val2, and then
press LntIr. See ligure 10-2. 1he sum ot 36.67 is displayed.
9. 1o multiply the tvo values together, type print "Product is " , val1 *
val2, and then press LntIr. See ligure 10-2.1he product ot 333.30 is displayed.
10. 1o subtract one value trom the other, type print "Difference is " ,
val1 - val2, and then press LntIr. See ligure 10-2. 1he ditterence ot 43.33
is displayed.
11. 1o take the square root ot each ot the tvo values, type print "Sguare
Root is " , sgrt{val1}, sgrt{val2}, and then press LntIr. See
ligure 10-2. 1he square root ansvers ot 7.07 and 2.38 are displayed. 1he
sqrt{| statement pertorms a tunction on the value betveen the parentheses.
12. 1o quit, type guit. 1his statement is required to exit bc.
13. Close your vindov, and then log out.
*MKuVe 10-2 9sMnK Lhe bc command Lo prompL Lhe user Lo enLer daLa rom Lhe keyboard
and perorm maLhemaLMcal operaLMons
SLep 8: adds values enLered
in SLeps 5 and 7
SLep 11: inds Lhe square
rooL o values enLered in
SLeps 5 and 7, respecLively
SLep 10: subLracLs values
enLered in SLeps 5 and 7
SLep 9: mulLiples values
enLered in SLeps 5 and 7
39 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
UsMRK XLe AVbMXVaVy 4VecMsMoR CalculaXoV Xo 4eVfoVm AVMXLmeXMc OTeVaXMoRs 395
6uRRMRK FG MR a ScVMTX
When you place bc in a script, you must run the script as tollovs
bc scr1t
1he bc command also allovs you to create arrays. 1hese vork in much the same vay
as they do in the shell. lor example, in bc, to set the value ot subscript 3 to 42 in an
array named array1, and then display the value on the screen, you enter
arrayl3=42
print arrayl3
Next you vill run bc commands in a script. lor example, say you vant to calculate the
average ot several grades to tvo decimal places.You have pertormed averages in an ear-
lier chapter, but you vere only able to vork vith vhole numbers. In this next exercise,
you vill the use the bc command vith a for loop, an array, and an average calculation
to determine an average to tvo decimal places.
1o usI bc to dItIrnMnI an avIragI to tvo dIcMnal placIs
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named bc in your $HOME/bin directory.
3. Insert the tolloving lines ot code to set the scale to tvo decimal positions
and to set a variable named max to 3. 1he variable named max contains the
maximum number ot grades that can be entered.
scale=2
max=3
4. Insert the tolloving lines ot code to create the loop, read a value in the array
named grade, and accumulate a total. Note the variable named tot is the accumu-
lated total. Notice the for statement uses lett and right curly brackets, {...},
instead ot a do...done pair that the bash shell uses. 1hese are required vhen
you have several statements that are part ot the iteration. All ot the statements are
pertormed tor each iteration ot the loop.
for {i=1 , i<=max , i++} {
print "Enter value: ", gradei]=read{}
tot=tot+ gradei]
}
3. Insert the tolloving lines ot code to compute the average, display the average,
and quit bc vhen the script completes. 1he \n in the print "\nAverage
is: " , avg statement causes a nevline to be generated betore the average
is printed.
avg = tot / max
print "\nAverage is: " , avg
guit
10
6. Save the script, close the editor, and then make the script executable.
7. 1o run the script, type bc -g bc5, and then press LntIr. 1he script prompts
you to enter values.
8. Lnter these three values vhen prompted 100, 88, and 8. See ligure 10-3.
1he average, 83.33, is displayed.
9. Perun the script. And then enter these three values vhen prompted 980,
1000, and 733. See ligure 10-3. 1he average, 91.44, is displayed.
10. Perun the script, and then enter these three values vhen prompted , 10,
and 1. See ligure 10-3. 1he average, 10.00, is displayed
11. Close your vindov, and then log out.
When usin Lhe bc command and speciyin Lhe subscripL in an array, you
don'L need Lo precede Lhe subscripL name wiLh a dollar sin as you do when
you reer Lo a subscripL in Lhe bash shell. For example, arraynamevar is
correcL, buL arrayname$var eneraLes a synLax error in bc.
6uRRMRK FG MR a 4MTelMRe CommaRH
1he bc command can be used in a pipeline command that pipes regular shell variables
to bc. 1ypically, you should run bc this vay instead ot in a script tor greater convenience.
lor example, it you have a script that is vritten in the shell and you vant to pipe vari-
ables to bc vhen you need arithmetic precision, you use the tolloving syntax
echo "{var1 oerat1on var2|" ] bc ~l
8MT
*MKuVe 10-3 9sMnK Lhe bc command wMLh a scrMpL
SLep 9: Lhree values and
Lheir averae
SLep 10: Lhree values and
Lheir averae
SLep 8: Lhree values and
Lheir averae
396 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
SeaVcLMRK foV 8exX UsMRK XLe KVIT CommaRH 397
1his is vhere var1 and var2 are shell variables that are passed to bc. 1he oerat1on
is a bc operation such as multiply, divide, add, or subtract. 1he bc command uses the
same arithmetic operators as the bash shell. Lverything betveen parentheses is consid-
ered a bc command and must adhere to its syntaxnot the shell`s syntax. Also, the ~l
(l as in library, option tells bc to use the math library tiles and is required vhen
piping data to bc.
Next you vill pipe shell variables to bc so bc can pertorm operations not ottered by
other commands.
1o pMpI shIll varMablIs to bc
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a data tile named ScrMptBC in your $HOME/bin directory.
3. Insert the tolloving lines ot code to establish the values, create the pipeline
using bc, and display the result ot the pipeline on the screen
value1=10.50
value2=10.70
answer=`echo "{$value1 + $value2}" [ bc -l`
echo $answer
4. Save the script, quit the editor, make the script executable, and then execute
the script. Notice that the resulting value 21.20 is displayed on the screen.
3. Close your vindov, and then log out.
7)A6CHIN+ *O6 8)X8 9SIN+ 8H) KVIT 'OMMAND
1he Iinux operating system allovs you to search tor text vithin a tile using the grep
command. 1he grep command prints matching patterns in a tile. lor example, it you
could not remember the name ot a tile that contained a piece ot data but you remem-
ber the actual data, you vould use the grep command. 1he general syntax is
grep ot1ons attern f11ename
As vith many Iinux commands, the grep command has numerous options. One use-
tul option is ~i vhich ignores the case you are matching. Because the shell is case sen-
sitive, it you search tor Smith, but it is entered as SMI1H in the tile, grep vithout
the ~i option vill not tind it. It you use the ~i option to ignore the case, then grep
vill tind Smith or SMI1H in this example. 1he attern can be any character string
or a regular expression.1he f11ename is the tile in vhich you are attempting to locate
the pattern. lor example, to locate the name Smith in the tile sort.dat, you enter grep
"Smith" sort.dat. 1he grep command displays the vhole line containing the text
Smith, or it displays nothing it a match is not tound.
10
1he grep program uses regular expressions tor matching lines. A rIgular IprIssMon is
a metacharacter used to match a particular pattern that describes a set ot strings. You use
a regular expression operator to construct a regular expression. 1able 10-3 lists the
metacharacters that are used to construct regular expression operators and their meanings.
Next you vill use grep to search tor text vithin a tile.
1o usI grep connands
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a data tile named partsdat in your $HOME/bin directory.
3. Insert the tolloving lines ot code to create records. Lach line is a record vith
the Part Number, Name, and Quantity as tields, and colon delimited.
100:Saw:120
101:Hammer:102
102:Wrench:10
4. 1o display matching lines containing 101, type grep 101 parts.dat, and
then press LntIr. See ligure 10-4. 1he record tor the Hammer is displayed.
Note the entire line is displayed by detault.
3. 1o display matching lines containing 102, type grep 102 parts.dat, and
then press LntIr. See ligure 10-4. 1his time, the records tor Hammer and
Wrench are displayed because both match.
6. 1o display matching lines containing the number 102 vhen it appears at
the beginning ot a line in the tirst tield, type grep 102: parts.dat, and
then press LntIr. See ligure 10-4. 1he record tor Wrench is displayed
because it is the only record vith 102 at the beginning ot the line. 1he use
ot the caret assures a match at the beginning ot the line. Note the use ot the
colon tolloving the number. 1his is used to make sure that a match occurs
exactly tor 102 as the tirst tield. It you lett it ott, a number such as 1022 or
1023 could appear in the output.
MeXacLaVacXeV DescVMTXMoR
` NaLches characLers aL Lhe beinnin o a line
$ NaLches characLers aL Lhe end o a line
. NaLches a sinle characLer
* NaLches all characLers
characters NaLches any characLers beLween brackeLs
\characters Removes Lhe meanin o a meLacharacLer
8able 10-3 1he reKular expressMons operaLors used by Lhe grep command
398 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
URHeVsXaRHMRK XLe SXVeam )HMXoV 399
7. 1o display matching lines containing either S or H, type grep SH]
parts.dat, and then press LntIr. See ligure 10-4. 1he records tor
Hammer and Sav are displayed because both ot these lines match.
8. Close your vindov, and then log out.
9ND)6S8ANDIN+ 8H) 786)AM )DI8O6
Iinux provides a command, called sed, that allovs you to pertorm editing tasks similar
to vi at the command line. 1he sed command literally means stream editor. 1he
command reads a stream ot input trom a tile and processes it using text-editing com-
mands. 1he sed command operates on characters in a tile and uses regular expressions.
Lnlike the vi editor, vith the sed command, you can automate processes that you
might need to pertorm on a text tile.
lor instance, say that everyday you receive a tile electronically trom another company
that is then processed by your company, and then some ot the processed data is sent out
to your customers. 1he daily electronic tile has state codes abbreviated using tvo char-
acters. Susie Weatherstone, the vice president ot marketing, vants the tull state name
spelled out tor your customers. lor example, CA needs to be replaced vith
Calitornia and 1N needs to be replaced vith 1ennessee. Lntortunately, you don`t
receive the daily tile until around 6 p.m. vhen most users have lett tor the day. What do
you do You can vrite a program in C or COBOI vhich handles this situation, but it
vill also take a vhile to complete. Or, you can use the sed command to search tor the
*MKuVe 10- DMsplayMnK maLchMnK lMnes wMLh Lhe grep command
SLep 6: displays Lhe line
maLchin "102" aL Lhe
FIKMRRMRK o any line
SLep 5: displays lines
maLchin "102" in
any ield
SLep 4: displays Lhe line
maLchin "101" in
any ield
SLep 7: displays
maLchin lines conLainin
"S" or "H"
10
tvo-character state codes and replace them vith the state names. Because you can run
this program in the background, you can log out and go home.When you return to your
ottice the next morning, the process ot changing the tvo-character state codes to tull
state names vill have completed.
As you`ve already seen vith the bc command, the sed command has its ovn set ot com-
mands and syntax. 1he sed command takes care ot opening the tile, reading the input
stream, and closing the tile tor you. It completes the entire process in only one pass, mak-
ing it very etticient. lirst, the sed command reads characters in a tile and places them
in a temporary memory butter. 1his butter is called the pattIrn spacI because it is the
area, or space, that holds the text that is currently being processed. Once sed is through
processing the characters in the pattern space, the characters are removed trom the pat-
tern space, but not trom the tile. 1hen, sed reads the next line ot characters into the
pattern space, and processing resumes vith the nev characters. It repeats this process
until there are no more lines in the tile.
8ecause Lhe paLLern space holds a line o LexL rom Lhe ile, you can Lhink o
each line as a record. ln essence, Lhe paLLern space is like a variable LhaL con-
Lains a whole record.
Generally, you run the sed program as tollovs
sed ot1ons f11ename
UsMRK WIH OTXMoRs
By detault, sed prints all the lines in the tile. When you use the ~n option, sed only
prints matches. 1he ~f f11ename option runs sed commands in a f11ename. 1his is
usetul tor automating sed commands that are done routinely. lor example, in the pre-
vious state code example, you could vrite a sed script that pertorms this. 1hen, a user
could simply run the script to update the state names.1he ~e option allovs you to per-
torm multiple edits on a single line ot text.1he advantage here is speed because the sed
command has to make tever passes in the tile it you combine edits in a single line.
You are required Lo ive sed eiLher a command or Lhe name o a scripL ile
or opLions. Leavin eiLher o resulLs in a synLax error.
As previously mentioned, the sed command has a set ot its ovn commands, and they
are listed in 1able 10-4.You can also use these commands vith redirection operators to
create a nev tile.
8MT
8MT
00 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
URHeVsXaRHMRK WIH CommaRHs 01
1he sed command uses the tolloving structure tor matching regular expressions and
establishing the corresponding command action to be taken
/attern/ command~act1on
1he torvard slashes surrounding attern serve as a delimiter and indicate vhere the
pattern begins and ends.
9ND)6S8ANDIN+ WIH 'OMMANDS
Because the sed command has its ovn set ot commands, it`s a good idea to become
tamiliar vith hov the commands are used. A strong understanding ot the various sed
commands allovs you to create more povertul scripts and streamline your development
time. In this section, you vill look at some examples using the sed command. lor
instance, a store named 1he Hardvare Supply Store has a supplies tile that contains part
records.1he records include the tolloving tields that are colon delimited Part Number,
Supplier, Part Name, Price, and Quantity.1he sed command can be used to modity the
text vithin the supplies tile. ligure 10-3 shovs the contents ot the supplies tile.
CommaRH 4uVTose
p PrinLs Lhe currenL paLLern space Lo Lhe screen
d DeleLes Lhe currenL paLLern space
s/regu1ar~express1on/ NaLches regular~expression Lo characLers in Lhe paLLern
rep1acement/g space; i Lhere is a maLch, Lhen iL replaces Lhe regular~
expression wiLh replacement. 1he leLLer "s" represenLs
subsLiLuLe and Lhe leLLer "" means Lo make Lhe chane lobally
Lo all lines.
a\ text Appends text
c\ text Replaces, or chanes, lines wiLh text
i\ text lnserLs text
r f11ename Reads LexL rom f11ename
w f11ename WriLes Lhe paLLern space Lo f11ename
b 1aoe1 8ranches, or Lransers execuLion, Lo a 1aoe1
t 1aoe1 1esLs or a successul subsLiLuLion and branches Lo a 1aoe1 i
successul
: 1aoe1 Deines Lhe 1aoe1 or Lhe b and Lhe t commands
{ } 8eins and ends a block o commands
# comment lndicaLes a comment
8able 10- A ew o Lhe sed commands
10
8Le 4VMRX CommaRH
1he simplest and most usetul ot the sed commands is the print command. It allovs you
to print characters trom the current pattern space. lor instance, it you vanted to print
all the records in the supplies data tile, you enter the tolloving
sed ~n p supplies
Note there is a space betveen the ~n option and the p command. 1here is a hyphen
prior to the n option but not prior to the p command.1he ~n option, vhich allovs the
sed command to print only matched lines, is necessary because the detault behavior ot
sedis to print every line ot input. In this example, the p command tor print is speci-
tied, vithout this option, each line is printed tviceonce tor the detault behavior and
once tor the specitied p option. It is the ~n option that causes the lines to be displayed
only once. 1his behavior is atypical vhen compared to other Iinux commands, hov-
ever it is hov sed vorks. Nov, look at the tolloving example, vhere the ~n option is
omitted
sed p supplies
ligure 10-6 shovs the running ot the sed p supplies command. ligure 10-7 shovs the
running ot the sed ~n p supplies command. Compare these tvo tigures. Notice in
ligure 10-6 that the command, sed p supplies displays each line tvice. In ligure 10-7,
the command sed~npsupplies displays matched lines only once.
*MKuVe 10-5 1he supplMes daLa Mle conLenL
02 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
URHeVsXaRHMRK WIH CommaRHs 03
It`s important that you tully understand hov the sed command vorks vith the detault
behavior as vell as vith the required command or script that you must specity tor sed. It
you are still a little uncertain about hov the sed commands operate, your understanding
vill become more tully evolved as you learn about additional commands tor sed.
1he sed command also allovs you to pick and choose vhich text lines ot a tile to
process. 1able 10-3 includes a tev examples ot printing specitic lines using variations ot
the print command tor sed.
*MKuVe 10-7 SupplMes daLa Mle dMsplayed wMLh Lhe sed~np supplies command
~n opLion displays
maLched lines only once
*MKuVe 10-6 SupplMes daLa Mle dMsplayed wMLh Lhe sed p supplies command
10
Although the p option is used to print the lines, you could easily replace p vith another
option such as d tor delete.
Here are a tev more examples to consider. Lach ot the tolloving examples and its results
are shovn in ligure 10-8. 1o print the tirst three lines ot the supplies tile, you enter
sed ~n l,3p supplies
It you leave ott the ~n option, it prints the tirst three lines tvice and each ot the remain-
ing lines once because ot the detault print behavior.
1o print all lines containing the text Handy, tolloved by any characters, you enter
sed ~n '/Handy*/p' supplies
1he asterisk, or vildcard symbol, means to search tor any characters subsequent
to Handy.
1o print all lines vith a Part Number beginning vith 2 or 4 in the supplies tile,
you enter
sed ~n '/`2~4/p' supplies
1he caret, `, indicates that the match is made at the beginning ot the line.
1o print all lines vith amounts betveen one and tvo dollars, you enter
sed ~n '/\$l\./p' supplies
Note there is a period, or dot, atter the second backslash, \. In this case, the $ sign is
preceded vith a backslash so it is not used as the metacharacter listed in 1able 10-3. 1he
dot is preceded vith a backslash tor the same reason. So, this literally lists all lines con-
taining s1..
)xamTles DescVMTXMoR
1p PrinLs Lhe irsL line
$p PrinLs Lhe lasL line
1,5p PrinLs lines 1 Lhrouh 5
8,12p PrinLs lines 8 Lhrouh 12
/The*/p PrinLs lines LhaL have Lhe LexL "1he" ollowed by any characLers; Lhe asLerisk
serves as a wildcard
/`T/p PrinLs lines LhaL have a "1" as Lhe very irsL characLer on Lhe line
/2~4/p PrinLs lines LhaL have a "2" or "4"in Lhem
/`2~4/p PrinL lines LhaL bein wiLh a "2" or "4"
/v. /p PrinLs lines LhaL conLain a "V" ollowed by any sinle characLer and a space
8able 10-5 A ew sed prMnL examples
0 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
URHeVsXaRHMRK WIH CommaRHs 05
1o print all lines that have a 43, tolloved by a single character, enter
sed ~n '/43./p' supplies
Here, the dot is the metacharacter listed in 1able 10-3 and matches a single character.
You can also read data into a variable and pertorm matches vith the sed command
based upon the variable`s contents. 1his gives you the tlexibility ot alloving the user to
enter data trom the keyboard. In the next statements, variables are read trom the key-
board, and then the variables are used to match characters vith a sed command.
read ~p "Enter part number to view record: " PartNo
sed ~n "/$PartNo/p" supplies
read ~p "Enterpart name to view record: " PartName
sed ~n "/$PartName/p" supplies
ligure 10-9 displays the script named sedB. It uses the read command just shovn to
obtain input trom the keyboard. It also uses the sed command to demonstrate hov sed
can use the data entered trom the keyboard.
*MKuVe 10-8 LxecuLMon o several sed prMnL commands
10
lL is a ood idea Lo surround your paLLerns wiLh sinle quoLes or double
quoLes. WiLhouL Lhem, you may eL unexpecLed resulLs.
Next you vill execute various sed print commands.
1o usI sed connands
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a data tile named Inplo]IIsA in your $HOME/bin directory.
3. Insert the tolloving lines ot code. Lach line is a record vith Lmployee ID,
Name, and Salary as tields, and colon delimited. Be sure to save the tile, and
then close the editor.
1:Marge Hammer:100000
2:Doug Allister:45000
3:Vu Louis:40000
4. 1o understand vhat happens vhen you do not issue a valid command, type
sedemployeesA, and then press LntIr. See ligure 10-10. An error is gen-
erated because you are required to enter either a command or a script name.
3. 1o understand the detault behavior and display the employeesA tile, type sed
pemployeesA, and then press LntIr. See ligure 10-10. Notice that each
employee record in the tile is listed tvice due to the detault behavior.
8MT
*MKuVe 10-9 1he sed8 scrMpL whMch maLches characLers usMnK values enLered rom Lhe
keyboard
06 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
URHeVsXaRHMRK WIH CommaRHs 07
6. 1o suppress the detault behavior vith the ~n option, type sed-np
employeesA, and then press LntIr. See ligure 10-10. 1his time, each
employee is listed once because the ~n option only prints those lines explic-
itly indicated by the print command.
7. 1o print the last tvo lines, type sed-n2,3pemployeesA, and then
press LntIr. See ligure 10-10. 1he last tvo lines are displayed.
8. 1o print the last line, type sed -n '$p' employeesA. See ligure 10-10.
1he last line is displayed.
9. Close your vindov, and then log out.
8Le DeleXe CommaRH
You can use the sed delete command (d, to delete lines ot text vithin a tile.You don`t
use the ~n option vith the delete command.You only need to use the ~n option vhen
you are printing. 1hink back to 1he Hardvare Supply Store example. 1his store no
longer sells part number 220, vhich you may recall is 2x6s, as one ot its supplies. 1o
delete this supply trom the supplies tile, you enter
sed '/`220:/d' supplies
Note the use ot the caret betore the number 220 and the colon atter the number 220.
1hese are used to make sure the tirst tield is matched exactly.You can see in ligure 10-11
the supplies tile betore part number 220 is deleted and then atter it is deleted. Notice in
ligure 10-11 that the other remaining records are displayed.
*MKuVe 10-10 LxecuLMnK sed commands on Lhe employeesA Mle
SLep 5: resulLs o deaulL
prinL behavior; each line
prinLs Lwice
SLep 4: resulLs in error
because no command or
scripL name is included
SLep 7: prinLs lasL Lwo lines
SLep 8: prinLs lasL line
SLep 6: ~n opLion
suppresses deaulL
prinL behavior
10
Actually, the part number is not physically deleted trom the original tile. 1o ettectively
delete the text, you have to redirect the output to another tile, and then copy the out-
put tile back to the supplies original tile as shovn in the tolloving code
cp supplies supplies.old
sed '/`220:/d' supplies.old > supplies
In the previous code, supplies is copied to supplies.old. 1he tile, supplies.old, becomes
the one on vhich the sed delete command is operating. 1hat result is then redirected
back to supplies, vhich then has all the records except the one that has been deleted.
8Le SubsXMXuXe CommaRH
1he sed substitute command (s, is usetul tor making changes to text. Pemember the ear-
lier state code-to-state name conversion example. 1he substitute command could have
been used to substitute the tvo-letter code tor the state`s name. Here`s another example
to consider. 1he supplier by the name ot 1he 1ool Shop changed its name to 1he 1ool
lactory.1o make that change using the sed substitute command, you enter the tolloving
sed 's/The Tool Shop/The Tool Factory/' supplies
As vith the delete command, the substitute command does not modity the contents ot
the original tile, in this case the supplies tile. 1o physically substitute the data, you have
to pertorm tvo commands as tollovs
cp supplies supplies.old
sed 's/The Tool Shop/The Tool Factory/' supplies.old >
supplies
*MKuVe 10-11 DeleLMnK LexL rom a Mle
08 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
URHeVsXaRHMRK WIH CommaRHs 09
1hese tvo commands are executed in ligure 10-12. 1he contents ot the supplies tile is
displayed vith the cat command betore and atter the tvo commands are executed.
Notice that betore the cp and sed commands are executed, the supplier 1he 1ool Shop
still exists, and atter the commands are executed, the name has been changed to 1he 1ool
lactory. 1he use ot redirection is carried out in the same vay as it is done vhen you
pertorm a deletion using sed.
8Le ATTeRH CommaRH
1he sed command also allovs you to append text belov any line vith the append com-
mand, (a,. lor example, it you vant to display a message indicating savs are 10 ott,
you enter
sed '/:Saw:/a\
* Saws l0% off this week *' supplies
1echnically, Lhe above code is one command, buL you musL place Lhe LexL on
a second line, oLherwise you receive an error. Sinle quoLes surround Lhe LexL
sLarLin wiLh "/:Saw:..." and ending with "...this week*". Also,
noLice LhaL asLerisks are used Lo visually call aLLenLion Lo Lhe sale and noL as
meLacharacLers. Fiure 10-13 shows Lhe sed append command. 1he append
command always places LexL below Lhe line LhaL is maLched.
8MT
*MKuVe 10-12 1he sed subsLMLuLe command
10
Notice the text Savs 10 ott this veek immediately tolloving the line vith the
text :Saw:. 1he original tile is lett intact.
8Le IRseVX CommaRH
You can insert text using the sed insert command (i,.1he insert command places text
above the line that it matches. Pecall that the append command places text belov the
line that it matches. lor example, it you vanted to insert text indicating that the sup-
plier named Kit is planning to raise prices, you enter
sed '/Kitchens by Kit/i\
* Kit will raise prices soon *' supplies
Iike the append command, you must place the text on a second line, othervise you
receive an error. ligure 10-14 shovs the sed insert command. Also like the append
command, the insert command does not change the original tile`s contents.
Next you vill execute the sed delete, substitute, append, and insert commands. In this
exercise, you vill make a copy ot the employeesA tile to employees.old. 1hen, you vill
vork vith the employees.old tile and as necessary, redirect output to the original
employeesA tile, thus incorporating the changes into the original tile.
*MKuVe 10-13 1he sed append command
Appended line
Oriinal ile
1he sed command
and resulLin ouLpuL
10 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
URHeVsXaRHMRK WIH CommaRHs 11
1o usI sed dIlItI, substMtutI, MnsIrt and appInd connands
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Copy the Inplo]IIsA tile to a nev tile named Inplo]IIsold.
3. 1o delete Doug Allister`s record and redirect the results to the employeesA
tile, type sed '/Doug Allister/d' employees.old > employeesA,
and then press LntIr. 1he prompt returns. Because the output ot the com-
mand is redirected to a tile, there is no output displayed.
4. Display the contents ot the Inplo]IIsA tile. Doug Allister`s record does
not appear.
3. Copy the Inplo]IIsA tile to the Inplo]IIsold tile again.
6. 1o change Marge Hammer`s name to Marge Stevens using substitution, and
then redirect the results to the employeeA tile, type sed 's/Marge
Hammer/MargeStevens/' employees.old> employeesA, and then
press LntIr.
7. Display the contents ot the Inplo]IIsA tile. Notice that Marge`s name has
changed.
8. Copy the Inplo]IIsA tile to Inplo]IIsold again.
9. 1o add a nev hire to the employees tile as the last record in the tile, and then
redirect the results to the employeesA tile, type the tolloving lines ot code.
sed '$a \
5:Lin Tuan:75000' employees.old > employeesA
*MKuVe 10-1 1he sed MnserL command
10
10. Display the contents ot the Inplo]IIsA tile. Notice that the record tor
Iin 1uan has been added.
11. Copy the Inplo]IIsA tile to the Inplo]IIsold tile again.
12. 1o add another hire to the employees tile, insert it betore the record vith
Lmployee ID 3, and then redirect the results to the employeesA tile, type the
tolloving lines ot code. Note that you must type the nev record tolloving
the right arrov prompt.
sed '/5/i \
4:Jenny Santiago:85040' employees.old > employeesA
13. Display the contents ot the Inplo]IIsA tile. See ligure 10-13. 1he record
tor enny Santiago has been inserted.
14. Close your vindov, and then log out
'6)A8IN+ WIH 7C6I48S
You might consider setting up a script vhen you have a set ot sed commands that you
vant to run automatically vith a text tile. Or, you might vant to place commands in a
script tile that generate a report.When placing sed commands in a script tile, you have
to run the commands using the tolloving tormat
sed ~f scr1t~name data~f11ename
*MKuVe 10-15 FMnal resulL o Lhe employeesA Mle
SLep 13: Jenny SanLiao
record has been added
Lo ile
12 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
CVeaXMRK WIH ScVMTXs 13
1he ~f option indicates that a sed script name tollovs.1he scr1t~name is the name
ot the sed script. 1he data~f11ename is the name ot the data tile. Iook at the script
shovn in ligure 10-16. 1he Hardvare Supply Store vants a simple report vritten trom
the supplies data tile.
In this script, any line preceded by a # sign is a comment. 1he tirst sed command li\
inserts the lines, 1ransaction Peport and the separator line, --------------------,
one line above. 1he backslash is required at the end ot each line in a multiple line sed
command. Ieaving it out results in an error. 1he next sed command, /:/i\ , inserts a
blank line betveen records, this is specitied by the single backslash on the line by itselt.
1he s/:/ /g command globally searches tor all colons and replaces them vith a space
or blank. 1his is done tor readability.
AnoLher way Lo achieve reaLer readabiliLy is wiLh Lhe 1ab key. You can press
Lhe 1ab key Lo cause Labs Lo be placed beLween ields. You press Lhe 1ab key
in Lhe replacemenL ield beLween Lhe second and Lhird orward slashes which
resulLs in: s/://g.
1he last command, $a\, appends the line, Lnd ot Peport , atter the last line
in the tile, vhich is represented by the dollar sign.
Next you vill create a sed script to become more tamiliar vith these concepts.
1o crIatI a sed scrMpt fMlI that vMll bI usId to gInIratI a rIport fron a data fMlI
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a tile named SIdLnp in your $HOME/bin directory.
8MT
#ReportTitle
1i\
TransactionReport\
~~~~~~~~~~~~~~~~~~~~~
#Insertablanklinebetweenrecords
/:/i\
\
#Replaceallcolonswithaspace
s/://g
#Appendtotheendofthefile
$a\
***EndofReport***
*MKuVe 10-16 1ransacLMon ReporL scrMpL
10
3. Insert the tolloving lines ot code to create the report title lines
# Insert the report lines above the first line.
1i\
\
Employee Report\
--------\
ID Name Salary\
-- ---- ------\
4. Insert the tolloving lines ot code to indicate a name change tor Marge
# Indicate that Marge Stevens had a name change.
/1:/a\
* Recent name change *
3. Insert the tolloving lines ot code to indicate a promotion and phone number
change tor Iin 1uan
# Indicate Lin Tuan's promotion and new number.
/Lin Tuan/ a\
* Recently promoted to Manager \
Her new extension is X1173 *
6. Insert the tolloving lines ot code to place a blank line and replace the colon
vith tvo tabs. 1hese are tor making the report more visually appealing. Note
that there is a blank line atter the /:/a\ line.
/:/a\
# Search for a colon and globally replace it with two tabs.
s/:/ /g
7. Insert the tolloving lines ot code to indicate the report`s end
# Indicate the report's end after the last line.
$a\
\
*** Report End ***
8. Save the script, and then close the editor.
9. 1o run the script, type sed -f SedEmp employeesA, and then press LntIr.
1he results ot the SedLmp script are shovn in ligure 10-17.
10. Close your vindov, and then log out.
A sed scripL is noL Lhe same Lhin as a shell scripL. A sed scripL only conLains
sed commands.
8MT
1 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
CVeaXMRK WIH ScVMTXs 15
UsMRK WIH CommaRHs MR SLell ScVMTXs
You can also integrate sed commands vith other Iinux operating system commands
vithin shell scripts.1his allovs you to take advantage ot the teatures ot sed that are not
provided by other commands. Probably the most povertul use ot the sed command is
that it can be used as a pipeline command.Although you can pertorm editing techniques
vith vi, you cannot use vi commands in a shell script, nor can you use it as a pipeline
command.
1ake a look at one ot the script statements ot a script called sed6 shovn in ligure 10-18
that uses the sed command as a pipeline.
price=${echo $tprice ] sed 's/\$//g'|
1his statement uses command substitution to set the variable named price.1he variable
named tprice, tor temporary price, is echoed and piped to the sed command.
In the second part ot the pipeline statement, sed 's/\$//g', the sed command glob-
ally substitutes a dollar sign and replaces it vith nothing. 1his is so a calculation can be
done.You cannot pertorm calculations on a variable containing a dollar sign. Hence, the
result ot the statement is the variable price containing a number vithout a dollar sign
that can nov be used in calculating the total.
1he next statement in ligure 10-18, subtotal=`echo "{$price * $qty|" ] bc~l`,
sets the variable subtotal to be the price times the quantity.1his product is echoed and piped
to the bc command. Because the bc command vorks vith decimal numbers, you get a
more precise value than it you just pertormed multiplication vithin the shell itselt.
*MKuVe 10-17 1he employee reporL Mle KeneraLed usMnK Lhe SedLmp scrMpL
10
1he statement total=`echo "scale=2, {$subtotal * $tax|" ] bc ~l` per-
torms the tinal calculation tor the variable named total. 1he portion ot the statement
scale=2 sets the decimal places to tvo digits.
ligure 10-19 shovs the contents ot the shell script named sed6 trom ligure 10-18, as
vell as the results ot various runs ot the sed6 script.You can compare the contents ot
records in the tile to the output. lor example, tor Part Number 101, the price is s13.32
and the quantity is 10. With a 6 tax, the total is s164.31 as shovn in the tigure. Also,
notice that the script uses a decision statement to determine vhether or not the Part
Number is in the tile. It not, then a message is displayed.
*MKuVe 10-19 sed6 scrMpL and ouLpuL o Lhree sample execuLMons
sed6 scripL
1hree sample
execuLion runs
tax=1.06
read ~p "Enter Part Number: " PartNo
# Rec contains the line which matches the Part Number entered.
Rec=`echo $PartNo ] sed ~n /`$PartNo:/p supplies`
if $Rec != ""
then
tprice=`echo $Rec ] cut ~d: ~f4`
qty=`echo $Rec ] cut ~d: ~f5`
price=${echo $tprice ] sed 's/\$//g'| # Search for $ and replace with space.
subtotal=`echo "{$price * $qty|" ] bc ~l`
total=`echo "scale=2, {$subtotal * $tax|" ] bc ~l`
echo "The total is: " '$'$total
else
echo "Record not on file"
fi
*MKuVe 10-18 Shell scrMpL wMLh sed commands
16 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
CVeaXMRK WIH ScVMTXs 17
Next you vill incorporate sed commands into a shell script. Lach employee in the
employeesA tile is to receive a 4 raise. You vant to open the employeesA tile, and read
each line as a record into LmpPec.1hen, you vant each ot the three tields, LmpID, Name,
and Salary, to be cut and placed into variables.
1o crIatI a shIll scrMpt that MncorporatIs sed statInInts
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named Salar]RaMsI in your $HOME/bin directory.
3. Insert the tolloving lines ot code to begin a while statement that reads
intormation into the LmpPec tile
while read EmpRec
do
4. Insert the tolloving lines ot code to cut the individual tields trom the record
EmpID=`echo $EmpRec [ cut -d: -f1` # Field 1
Name=`echo $EmpRec [ cut -d: -f2` # Field 2
Salary=`echo $EmpRec [ cut -d: -f3` # Field 3
3. Insert the tolloving line ot code to increase the salary by tour percent.
Notice that the scale is set to allov tor tvo decimal places.
NewSal=`echo "scale=2, {$Salary * 1.04}" [ bc -l`
# Give a 4% raise.
6. Insert the tolloving lines ot code to append the employee ID, Name, and Nev
Salary to the employee.nev tile, and then complete the while statement.
echo ${EmpID}:${Name}:${NewSal}>> employee.new
# Rewrite to a new file.
done < employeesA
7. Save the script, close the editor, and then make the script executable.
8. Lxecute the script.
9. Display the contents ot the employee.nev tile. 1he contents ot the tile appear
vith the nev salary amounts.
10. Close your vindov, and then log out.
UsMRK WIH Xo MoHMfy CommaRH OuXTuX
One ot the greatest advantages ot WIH is the ability to use its commands on the output
ot other Iinux commands. lor instance, a group ot users have a ditticult time discern-
ing a directory trom a tile. 1he goal is to make the output ot the ls ~l command a lit-
tle more user-triendly. 1o accomplish this, a directory can be indicated tor the ls ~l by
having the text Directory replace the letter d that exists at the tar lett ot a long list-
ing. A tile can be indicated by replacing the dash vith the text lile.1he output ot the
10
ls ~l command can be piped to the sed command vhich modities the output. 1his
can all be achieved using the tolloving code
ls ~l ] sed ~e 's/`d/Directory /' ~e 's/`~/File /'
ligure 10-20 shovs a regular run ot the ls ~l command, and the results atter making
the above changes using the sed command in a script named sed101. 1he letter d is
replaced by the text Directory as long as d is the tirst letter (this is determined by
using the caret `, ot a line ot text.1he character - is replaced by the text lile. Note
that the home directory tor user toddm is shovn.1he directories and tiles in your home
directory may be ditterent, but the output ot the command vill be similar.
Next you vill place the text Lmployee logged in to the lett ot the logged-in user-
name. 1he output ot the who command is piped as input to the sed command.
1o usI sed to nodMf] thI output of othIr connands
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. 1o modity the output ot the who command vith sed, type who [ sed
's// Employee logged in: /', and then press LntIr. 1he text
Lmployee logged in appears to the lett ot the user`s name.
3. Close your vindov, and then log out.
*MKuVe 10-20 OuLpuL o Lhe ls ~l command and MLs ouLpuL modMMed wMLh sed
18 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
URHeVsXaRHMRK SMKRals 19
9ND)6S8ANDIN+ 7I+NALS
1he shell uses signals to control the processing ot jobs. A sMgnal is a message sent to a
process trom another process such as the shell or a program. 1here are several types ot
signals. 1he most important ones are listed in 1able 10-6.
1o see all o Lhe sinals, you need Lo view Lhe conLenLs o Lhe ile
/usr/include/asm/sinal.h, or run Lhe kill ~l command.
1he tvo main concepts you need to understand regarding signals are hov to send them
and hov to catch them. Signals are sent using the kill command, and they are caught
using the trap command.
8Le OMPP CommaRH
1he kill command can be used to send a signal to a process. 1here are other vays in
vhich a signal can be sent. lor instance, you can press CtrlC to quit a process. You can
press CtrlS to stop a process, or you can press CtrlQ to continue the process. All ot
these actions are signals sent to a process. 1he kill command takes the tolloving gen-
eral torm
kill s1gna1 PIb
1his is vhere s1gna1 is a signal number and PIb is the process ID ot the process to kill.
It you need to tind out the PID ot a job, you run the ps command to display it. Once
you knov the PID, you can send a signal to it. Next you vill use a command named yes
that displays the text y on the screen intinitely. Note that the yes command is very
CPL intensive.You should run it on a computer system vhen no other users are on it.
1hen, you vill determine the PID ot a process, and tinally terminate the process.
8MT
SMKRal NumbeV SMKRal Name DescVMTXMoR
1 SlGHUP Hanup, such as a user loin ouL
2 SlGlN1 lnLerrupL rom Lhe keyboard
3 SlGQUl1 QuiL rom Lhe keyboard
9 SlGKlLL Kill sinal; you cannoL prevenL Lhe kill sinal rom LerminaLin
a process
14 SlGALARN Alarm sinal used or Limin ouL a process
15 SlG1LRN 1erminaLion
8able 10-6 LMsL o MmporLanL LMnux sMKnals
10
1o undIrstand hov to dItIrnMnI a PID and tIrnMnatI a procIss
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. 1ype yes, and then press LntIr. 1his command displays the text y on the
screen intinitely, or until it is killed.
3. Open another 1erminal emulation vindov.
4. 1ype ps -a [ grep yes, and then press LntIr. 1he ps command vith the
~a option displays all processes. 1his output is piped to the grep command
vhich searches tor the text yes anyvhere in the output ot the ps command.
Pemember, your other vindov is still running the yes command, so the
ps ~a ] grep yes command displays output similar to the tolloving
l67l pts/2 00:0l:0l yes
1he tirst number is the PID, or 1671 in the example shovn. 1he text yes is
the command that is continually running.
3. 1ype kill4-(, and then press LntIr. Be sure to substitute your PID num-
ber tor PIb. Nov, look at the vindov that had been running the yes com-
mand. 1he command has terminated and the message 1erminated appears
on the screen.
6. Close both vindovs, and then log out.
8Le XVET CommaRH
1he trap command catches, or traps, a signal to a process. You use this command to
intercept a signal. One application is to use the trap command to prevent a signal trom
stopping a running script. You can either display a message or execute a program vhen
the signal is trapped. lor example, vhen a user presses CtrlC, signal number 2 is sent
to the script, thereby terminating it. You can prevent termination by trapping signal
number 2. 1he trap command takes the tolloving general torm
trap argument s1gna1
1his is vhere argument is a command to be executed or a message to be displayed in
the event the running script, or job, receives the specitied s1gna1. Next you vill trap
a signal.
1o undIrstand hov to trap a sMgnal
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named 1rapIt in your $HOME/bin directory.
20 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
6evMew QuesXMoRs 21
3. Insert the tolloving lines ot code. 1he second command traps signal 2 (vhich
is specitied at the end ot this statement, and displays Caught CtrlC vhen
it receives this signal number. 1he command portion ot the trap command
is "echoCaughtCtrl~C". (You must surround the command in quotes
because ot the quoting rules specitied in Chapter 4.,
#!/bin/bash
trap "echo Caught Ctrl+C" 2
yes
4. Save the script, close the editor, and then make the script executable.
3. Press Ctrl+C to quit the process. 1he message Caught CtrlC is displayed
on the screen.
6. Close your vindov, and then log out.
'HA48)6 7UMMA6Y
1he shell allovs you to use the bc command to pertorm precise arithmetic using
decimal numbers.You can run bc interactively, in a script or in a pipeline.
1he grep command allovs you to display lines in a tile that match a pattern. A
regular expression uses metacharacters to match at the beginning ot a line, the end
ot a line, or match a character in a range.
1he sed command is a text-editing tool vith vi editing capabilities. 1he benetit
ot sed is that you can use it to pertorm commands automatically.
1he sed command has its ovn command language.You can print, delete, search,
substitute, append, or insert text using sed.
1he sed command can also be combined vith scripts.You can create a set ot sed
commands and use the ~f option to run the sed script.You can also use sed com-
mands in scripts as vell as in a pipeline process.
Signals are messages the shell uses to manage a script or program.You use the kill
command to send a signal to a script, and you use the trap command to capture a
signal and act on it. 1he SIGKIII signal cannot be caught or ignored. Lven it your
script is set to trap tor this signal, it it receives a SIGKIII, the script vill terminate.
6)VI)W 5U)S8IONS
1. 1he command allovs you to pertorm precise calculations.
a. sed
b. readonly
c. bc
d. grep
10
2. 1he command allovs you to only pertorm searches.
a. sed
b. search
c. bc
d. grep
3. 1he metacharacter makes a regular expression that allovs you
to match at the beginning ot a line.
a. $
b. >
c. <
d. `
4. 1he metacharacter makes a regular expression that allovs you
to match at the end ot a line.
a. $
b. >
c. <
d. `
3. 1o set the number ot decimal places to tvo in the precision calculator, use
.
a. precise=4
b. scale=4
c. decimal=4
d. Scale4
6. 1o set the precision calculator to quiet mode, use .
a. ~q
b. ~l
c. ~scale
d. ~v
7. 1he command is used to send a signal to a process.
a. XVET
b. OMPP
c. IGLS
d. GLQSH
22 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
6evMew QuesXMoRs 23
8. Which command is used to catch a signal sent to a process
a. trap
b. kill
c. shift
d. chmod
9. What signal cannot be caught
a. 9
b. 1
c. 2
d. SIGAIAPM
10. What signal number is represented by SIGQLI1
a. 9
b. 1
c. 2
d. 3
11. 1he metacharacter makes a regular expression that allovs you
to match a single character position.
a. .
b. *
c. \
d. `
12. 1he metacharacter makes a regular expression that allovs you
to match all character positions.
a. .
b. *
c. \
d. `
13. 1o run the precision calculator vith the math library, use the
option.
a. ~q
b. ~l
c. ~scale
d. ~v
10
14. 1he sed command used to delete a line is .
a. d
b. p
c. s
d. i
13. 1he sed command used to print a line is .
a. d
b. p
c. s
d. i
16. 1he sed command used to substitute a line is .
a. d
b. p
c. s
d. i
17. 1he sed command used to insert a line is .
a. d
b. p
c. s
d. i
18. 1he sed command used tor a comment is .
a. &
b. *
c. #
d. `
19. 1he sed option used to run commands in a tile is .
a. ~l
b. ~q
c. ~s
d. ~f
20. Which command calculates monthly salary trom an annual salary amount
a. NewSal=`echo "scale=2, {$Salary / l2|" ] bc ~q`
b. NewSal=`echo "scale=3, {$Salary / $NumMonths|" ] bc ~l`
c. NewSal=`echo "scale=2, {$Salary / l2|" ] bc ~l`
d. NewSal=`echo "scale=2, {$Salary ** l2|" ] bc ~l`
2 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
HaRHs-oR 4VoNecXs 25
,ANDSON 46OJ)C8S
4VoNecX 10-1
In this project, you vill send and catch various signals by creating a script that traps sig-
nals.You vill use a looping structure to have the script run indetinitely. (1his is to give
you enough time to send a signal to it., You vill use the while...do...done com-
mand to structure your loop.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named ProNIct10-1 in the $HOME/bin directory.
3. 1ype the tolloving lines ot code to create the intinite loop
while :
do
trap "echo Got signal 2" 2
trap "echo Got signal 3" 3
trap "echo Got signal 9" 9
done
4. Save the script, close the editor, and then make the script executable.
3. 1ype $HOME/bin/Project10-1& to run the job in the background using the
& symbol, so the job remains available as a process you can signal.
6. Pecord the output. (Hint 1he second number is the PID.,
7. 1ype kill -2 4-( to send a signal to the PID. (1his is vhere PIb is the second
number you tound in Step 6.,
8. Pecord the output.
9. Send signal 3 to the same PID.
10. Pecord the output.
11. Send signal 9 to the same PID.
12. Pecord the output.
13. Close all vindovs, and then log out.
4VoNecX 10-2
In this project, you vill pipe values to the bc command to keep track ot patients and
their temperatures.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named ProNIct10-2 in the $HOME/bin directory
3. Add the necessary code to allov a user to enter patient names and patient temper-
atures tor tive days. Lse the shell`s read command tor data input. See 1able 10-7
tor a list ot patients and their temperatures taken over the tive day period.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
10
4. Average the tive temperatures using bc.
3. Write each patient`s name, the tive temperatures, and the average to a tile named
PatMIntsdat.
6. Save the script, close the editor, make the script executable, and then execute
your script.
7. Close your vindov, and then log out.
4VoNecX 10-3
In this project, you vill pertorm pattern-matching techniques using the grep command.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a data tile named ProNIct10-3dat in the $HOME/bin directory.
3. Place the tolloving three records in the tile (the tields tor these records are
Lmployee IDDepartmentNameSalary,
100:MIS:Micki McSunday:45000.50
103:ENG:Zachary Scott:40122.44
104:ACC:Jessie Garcia:50000.01
4. Create a script named ProNIct10-3 in the $HOME/bin directory.
3. Write the code needed to pertorm the tolloving. Lse the case statement to cre-
ate a menu. Lsers should be able to enter 1 to search tor a name, 2 to search
tor an Lmployee ID, 3 to search tor a department, and 4 to exit the script. Lse
grep to pertorm the pattern matching.You may need to use double quotes vhen
searching on the variable names.
6. Save the script, close the editor, make the script executable, and then execute
your script.
7. Close your vindov, and then log out.
4VoNecX 10-
In this project, you vill pertorm text-processing techniques using the sed command.
You vill use the data tile created in Project 10-3.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
4aXMeRX Name Day 1 Day 2 Day 3 Day Day 5
Joe ARXMKua 1002 99 1025 986 991
SaRHy &VouKLXoR 995 987 1022 999 986
Amy &Vock 986 996 1005 1002 1011
MaVy WalscL 999 1022 10350 10275 10100
8able 10-7 PaLMenL LemperaLures
26 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
HaRHs-oR 4VoNecXs 27
2. Create a script named ProNIct10-4 in the $HOME/bin directory.
3. Create a menu-based script using the case statement. Option C or c allovs
users to pertorm a name change. Option D or d allovs users to delete a
record. Option S or s (tor Shov Pecords, shovs all records in the tile. Option
X or x exits the menu.You need to update the tiles, so make copies ot the tile
and redirect output as necessary.
4. Save the script, close the editor, make the script executable, and then execute
your script.
3. Close your vindov, and then log out.
4VoNecX 10-5
In this project, you vill use tile processing and precision calculations using the bc com-
mand. You vill use the data tile created in Project 10-3.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named ProNIct10- in the $HOME/bin directory.
3. Create a script that reads the records in the tile created in Project 10-3 and vrites
records to a nev tile. A record in the nev tile needs to contain these tields
Lmployee ID and a nev amount tor the Salary. 1he nev salary amount needs to
be the salary plus a tive percent raise. lor example, it the salary is s60,000, then
the nev amount vritten vould include the tive percent raise bringing the salary
to s63,000.
4. Save the script, close the editor, make the script executable, and then execute
your script.
3. Close your vindov, and then log out.
4VoNecX 10-6
In this project, you vill create a report using the sed command.You vill use the data
tile created in Project 10-3.You may have to recreate the tile it you deleted records con-
taining the data in Project 10-4.You vill also create a sed script tile and execute it using
the ~f option.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named ProNIct10- in the $HOME/bin directory.
3. Create a Personnel Peport using the teatures ot sed. Create an appropriate report
heading and end line. Important tacts to indicate in your report the MIS depart-
ment is only a month old. It employees are in the MIS department, indicate they
are nevly hired. essie in accounting just got a promotion to the Phoenix ottice.
Zachary in engineering just had his 13
XL
year anniversary vith the company.
4. Save the script, close the editor, make your script executable, and then execute
your script.
3. Close your vindov, and then log out.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
10
4VoNecX 10-7
In this project, you vill use the bc command to pertorm calculations tor a nev mall
store called It`s Your Clothing Store.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named ProNIct10-7 in the $HOME/bin directory.
3. Create a script composed completely ot bc statements. 1he script needs to use a
looping structure. Allov the user to enter the number ot times to loop. Allov the
user to enter a tax amount. Allov the user to enter the price and quantity tor
apparel. Lse tvo decimal places. Calculate the subtotal as price multiplied by
quantity. Include the tax in the total. When data is entered, the script needs to dis-
play the subtotal, tax, and total tor each iteration.
4. Save the script, close the editor, make your script executable, and then execute
your script.
3. Close your vindov, and then log out.
4VoNecX 10-8
In this project, you vill read a record trom a tile containing payroll data.You vill then
use the bc command to pertorm pay calculations.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named ProNIct10-8 in the $HOME/bin directory. 1he script needs
to read in tive employee records using a loop. (HintYou might need to reter to
Chapter 9 tor more intormation regarding tile processing., Peter to 1able 10-8
tor a table ot the employee records to use. Notice that the tields are comma
delimited. lor each record, calculate gross pay.You are to account tor regular pay
and overtime pay in your calculations. Lse the bc command to pertorm the cal-
culations. Set the scale to tvo decimal positions. Here is the code you vill need
to calculate the gross pay tor regular pay calculations
gp=`echo "scale=2, {$rate * 40|" ] bc ~l`
Once the gross pay is calculated, display the Lmployee ID, Name, Pate, Pay,
and Hours.
)mTloyee ID Name 6aXe HouVs
1 Li 1anlees 50.30 41
2 Frank Jones 44.50 43
3 Jay Haywood 50.55 44
4 Fran NarLel 40.00 40
5 Jen Vladosk 41.99 10
8able 10-8 Lmployee records
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
28 CLaTXeV 10 IRcoVToVaXMRK AHHMXMoRal 8ecLRMques aRH 8ools
Case 4VoNecXs 29
3. Save the script, close the editor, make your script executable, and then execute
your script.
4. Close your vindov, and then log out.
'AS) 46OJ)C8S
Case 10-1
1MI needs help vriting a script that calculates net pay. Hovever they need the data
to be precisely calculated. Pevrite the script trom Case 3-1 in Chapter 3 vith these
moditications
1. Prompt tor user input.
2. Implement a loop alloving the user to enter records until they no longer vant to
continue.
3. Don`t allov the user to terminate the script it they press CtrlC.
4. Calculate the Gross Pay, the Deductions, and the Net Pay amounts to the penny.
3. Display the Lmployee`s ID, the Gross Pay, all ot the deductions, and the Net Pay
in an appropriate manner.
Case 10-2
Darvood`s Doughnut and Bagel Shop needs a menu script that allovs the user to
1. Create a data tile vith the tolloving records Product ID, Product Name, Product
Price, and Supplier
2. Delete a product based upon Product ID
3. Change a Product Name
4. Display all Product Names
3. Print the data tile
'EWI
4VSNIGX
'EWI
4VSNIGX
10
31
',%48)6

%(:%2')( 8)',2-59)7
%2( 83307
-RXLMWGLETXIV]SY[MPP
9RHIVWXERHXLIawk TEXXIVRWGERRMRKERHTVSGIWWMRKPERKYEKI
TVSKVEQ
0IEVREFSYXawk TVSKVEQI\IGYXMSRERHGSQQERHWXVYGXYVI
+IXHEXEMRXSXLIawk TVSKVEQ
9WI awk WGVMTXW
;SVO[MXLXLIdialog GSQQERH
-QTPIQIRXQYPXMTPIHMEPSKFS\IW[MXLMREWGVMTX
-
n thMs chapter, you vMll learn hov to use the E[O program1he E[O program
Ms a complete programmMng language that allovs you to pertorm tasks
that other IMnux tools dontt provMde 1he advantage ot E[O Ms that you can
manMpulate tMelds vMthMn a record Mn a tMle, and pertorm decMsMon and loopMng
structures based upon patterns It combMnes the teatures ot WIH and KVIT that
allov you to search tor patterns, plus Mt provMdes programmMng technMques that
the shell otters Other tools alone cannot support these combMned teatures
You can use E[O to modMty the output ot IMnux shell commands allovMng
you to create custom scrMpts In thMs chapter, you vMll also learn about the
HMEPSK command vhMch allovs you to create graphMcal, user-trMendly menus
that can be Mncorporated Mn your scrMpts
9ND)6S8ANDIN+ 8H) E[O 4A88)6NSCANNIN+ AND 46OC)SSIN+
0AN+UA+) 46O+6AM
1he awk command vas named atter the three developers vho vrote it,Altred Aho, Peter
Weinberger, and Brian Kernighan. 1he awk progran is a programming language vith
decision and loop structures similar to vhat you`ve already used in the bash shell. In
tact, some ot the same statements you have used vithin the shell exist in awk as vell.
1he awk program allovs you to manipulate data vithin tiles, extract and compare tields,
print reports, and match regular expressions easier than other tools such as grep and
sed or even other shell commands. Although bash allovs you to pertorm decision
statements, loops, and other programming structures, it relies on other commands to
pertorm tile, record, and tield manipulation. Because these techniques are built into the
awk program, they execute taster than by implementing several ditterent commands to
accomplish the same task in the bash shell. Also, the awk program has its ovn variables
that it uses to keep track ot the current record number in a line or the number ot tields
in a record. 1hese variables are used as a record counter and are taster and easier to use
than incrementing a variable as you have seen in previous chapters.
1able 11-1 includes some ot the Iinux programs you`ve learned about and the techniques
they provide. Note the letter Y in a column indicates the technique is provided by the
program and the letter N in a column indicates the technique is not provided by
the program.You can reter to this table and quickly decide vhich program to use based
upon vhat you vant to accomplish. lor example, it you need to create a report tor
a data tile, you could use either awk or sed because there is a Y tor both programs
in that column. As you can see, awk provides tor all the techniques.
1he awk program also allovs you to pertorm numeric operations on real numbers
(numbers containing decimal points,, and it also has builtin tunctions, such as calculating
the square root. With the awk program you can use such regular expression techniques
as those used vith grep and sed vhich you learned about in Chapter 10.
LMRux *MelH 6eToVX DecMmal MaXLemaXMcal SeaVcLMRK DecMsMoR &uMlX-MR
UXMlMXMes MaRMTulaXMoR +eReVaXMoR 4VecMsMoR OTeVaXMoRs foV DaXa aRH couRXeVs
aRH wMXLMR a LooTMRK aRH
ComTaVMsoR *Mle SXVucXuVes vaVMables
awk Y Y Y Y Y Y Y
bash Y N N Y N Y N
bc N N Y Y N Y N
grep N N N N Y N N
sed N Y N N Y N N
8able 11-1 ComparMson o Lhe LechnMques provMded by varMous LMnux proKrams
32 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
LeaVRMRK AbouX E[O 4VoKVam )xecuXMoR aRH CommaRH SXVucXuVe 33
1he awk command can be executed the tolloving vay
awk ot1on rogram~text f11e
1he awk command allovs you to place an ot1on atter its name vhich can be any one
or a combination ot the options listed in 1able 11-2.1he rogram~text is a set ot awk
patterns andor actions. 1hese vill be discussed later in this chapter. 1he f11e is a tile
containing data that the awk command processes.
0)A6NIN+ %&OU8 E[O 46O+6AM )X)CU8ION AND 'OMMAND
786UC8U6)
1he awk command operates similarly to the sed program discussed in Chapter 10.1he
awk program reads lines ot input trom the keyboard or a tile and matches lines based
upon a pattern. It ditters trom sed in that awk allovs you to specity an action that is to
be pertormed on those matched lines.
1his section takes a look at some general guidelines governing patterns and actions
betore discussing each in greater detail. An awk command is composed ot a sequence ot
pattern and action statements. 1hink ot the pattIrn statInInt as vhat you vant to
match a record in the data tile vith and the actMon statInInts as vhat occurs vhen
a pattern is matched in a record in the data tile. Here is the general structure tor hov a
pattern and action are tormed
attern_to_match { act1on_to_take }
1he syntax ot awk requires you to enter at least one pattern or one action vhen using it.
You can enter both on the same line, but vhen you do, the pattern comes tirst tolloved
by the action. Action statements are enclosed vithin a pair ot braces, {.}. It you utilize
the awk command vithout the pattern, the action is pertormed tor each line ot input. It
you don`t include the action statements, all input lines matching the pattern are displayed.
OTXMoR DescVMTXMoR )xamTle
~fprogram~text LeLs you speciy a ile LhaL conLains awk~fawkscript
f11e awk commands Lo be execuLed employees.dat
~Ffs LeLs you speciy a ield separaLor awk~F:~fawkscript
as fs employees.dat
~vvar1ao1e=va1ue LeLs you pass values Lo awk; once awk~fawkscript~v
passed, awk can manipulaLe Lhem Amt=5
~Wopt1ons LeLs you use such opLions as help awk~Wversion
or version Lo prinL addiLional
inormaLion abouL awk
8able 11-2 Some o Lhe awk opLMons
11
4aXXeVRs
1here are quite a tev patterns in the awk language. Only the tolloving three patterns
vill be discussed here
Pegular expressions
BEGIN
END
8Le 6eKulaV )xTVessMoR 4aXXeVR
1he awk program allovs you to pertorm pattern matching using the regular expres-
sions discussed in Chapter 10 tor sed. When using regular expressions you need to
surround the regular expression vith a torvard slash, vithin single quotes, as in
'/regu1ar_exress1on/'.
Next you vill learn hov to use regular expressions vith awk. In this exercise and those
to come, you vill need to use a tile that contains records vith these tields Lmployee ID,
lirst Name, Iast Name, and Annual Salary.
1o usI rIgular IprIssMons vMth awk
1. Iog in to the Iinux system as a user, open a 1erminal emulation vindov, and
then change to the $HOME/bin directory.
2. lirst, you must create the data tile to be used. Create a data tile named
Inplo]IIsdat in your $HOME/bin directory and insert the tolloving lines
belov. Make sure you leave a space (not a colon, tor the tield separator
betveen each tield. 1he awk command uses a space as a separator.
1 Marge Smith 100000
2 Vu Lung 40000
3 Jenny Patel 85040
4 Lin Liu 45000
3. Save and close the Inplo]IIsdat tile.
4. 1o display the line containing the Lmployee ID starting vith 1, type awk '/
1/' employees.dat, and then press LntIr. Note the caret (, is used to
match at the beginning ot the line. Here, it is required to match Lmployee ID.
It you lett the caret ott, it vould display any line vith a 1 in it. See
ligure 11-1. 1he record tor Marge Smith is displayed.
3. 1o display the line containing Iin Iiu, type awk '/ Lin Liu /'
employees.dat, and then press LntIr. Be sure to include a space betore the
tirst name and atter the last name. See ligure 11-1. 1he record tor Iin Iiu
is displayed. Note that there is a space betore the name Iin and atter the
name Iiu. It you leave them out, the awk statement vould display Iin Iiuxyz
it it appeared in the tile. By including spaces, you are guaranteed to only get this
match tor the data in the employees.dat tile.
3 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
LeaVRMRK AbouX E[O 4VoKVam )xecuXMoR aRH CommaRH SXVucXuVe 35
6. 1o display lines vith employees earning a salary betveen s40,000 and
s49,999, type awk '/ 4..../' employees.dat, and then press LntIr.
Note there is a space betore the number 4. See ligure 11-1. 1he records tor
Vu Iung and Iin Iiu are displayed.
7. 1o display lines vith employees earning a salary ot betveen s40,000 and
s89,999 inclusive, type awk '/ 48]..../' employees.dat, and then
press LntIr. Again, there is a space prior to [48|. See ligure 11-1. 1he
records tor Vu Iung, enny Patel, and Iin Iiu are displayed.
8. Close your vindov, and then log out.
8Le &)+-2 aRH )2( 4aXXeVRs
Although most patterns are compared to a line ot input in the data tile, the BEGIN and
END patterns are not evaluated. 1hey contain statements that are executed. 1he BEGIN
pattern is executed betore any input is read. 1he END pattern is executed atter all ot the
input lines have been read. You can use the BEGIN pattern to display a heading line
betore all the records are printed, and then you can use the END statement to display an
ending atter all records have been printed.
1hink o Lhe BEGIN paLLern as a header and Lhe END paLLern as a ooLer.
8MT
*MKuVe 11-1 9se o awk reKular expressMons
SLep 4: usin Lhis search
paLLern is helpul or
searchin or employee
records usin Lhe
Lmployee lD as a primary
key ield
SLep 5: Lhis meLhod is
useul or indin
addiLional inormaLion
abouL an employee i
you do noL know Lhe
Lmployee lD
11
You musL Lype BEGIN and END in all uppercase leLLers.
Next you vill vork vith the BEGIN and END patterns.
1o usI BEGIN and END pattIrn-natchMng statInInts Mn thI awk progran
1. Iog in to the Iinux system as a user, open a 1erminal emulation vindov, and
then change to the $HOME/bin directory.
2. 1o display a heading line and match the tirst character in the range ot 1 to 4,
type awk 'BEGIN {print "ID First Last Salary"}, /1-4]/'
employees.dat, and then press LntIr. Note the use ot the caret in the pat-
tern /`l~4/ matches either a 1, 2, 3, or 4 in the tirst character position. See
ligure 11-2.1he heading line is displayed tolloved by the matching records.
3. 1o tirst display records then an ending line, type awk /1-4]/, END
{print "*** End of Report ***"}' employees.dat, and then press
LntIr. See ligure 11-2. 1he matching records are displayed tolloved by the
ending line you established in the code.
4. 1o display a heading line, input records tolloved by an ending line, type
awk 'BEGIN {print "ID First Last Salary"}, /1-4]/,
END {print "*** End of Report ***"}' employees.dat, and then
press LntIr. See ligure 11-2.1he tvo heading lines are displayed tolloved by
the matching records and tinally the closing line.
3. Close your vindov, and then log out.
*MKuVe 11-2 9se o Lhe awk, BEGIN, and END paLLern sLaLemenLs
SLep 2: Lhe use o square
brackeLs maLches a
speciied rane, in Lhis case
1 Lhrouh 4
8MT
36 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
LeaVRMRK AbouX E[O 4VoKVam )xecuXMoR aRH CommaRH SXVucXuVe 37
AcXMoRs
In awk, an action must be enclosed in braces and consists ot variable assignments, arithmetic
and logic operators, decision structures, andor looping structures.1he print statement is
an action. Also, the awk command uses statements similar to those used by the shell such
as if, while, and for.
UsMRK XLe TVMRX SXaXemeRX Xo )xXVacX *MelHs
As you have already seen in the earlier exercises, the print statement is an action state-
ment that prints tields in an input record. By detault, the entire line ot input is printed.
Hovever, you can control vhich tields are printed. Next you vill learn hov to use the
print action statement in awk to extract specitic tields. In awk, each column ot input is
reterred to as a positional parameter. In other vords, the tirst tield is $l, the second tield is
$2, and so on.1he positional parameter $0 represents the entire line ot input.
ln awk, as in Lhe bash shell, $l, $2, and so on are called posiLional
parameLers.
1o usI thI print actMon statInInt Mn awk
1. Iog in to the Iinux system as a user, open a 1erminal emulation vindov, and
then change to the ,31)FMR directory.
2. 1o display all tields, type awk '{print $0}' employees.dat, and then
press LntIr. See ligure 11-3. All tields ot all input lines are printed.
3. 1o display the lirst and Iast Name tields, type awk '{print $2, $3}'
employees.dat, and then press LntIr. See ligure 11-3. 1he lirst and Iast
name ot all input lines are displayed.
4. You can also change the display order ot the tields. So, to display the Iast Name
tolloved by the lirst Name, reverse the positional parameters by typing
awk '{print $3, $2}' employees.dat, and then press LntIr. See ligure
11-3.1he Iast Name and then the lirst Name tor all input lines are displayed.
3. 1o display the Iast Name tirst, tolloved by the Lmployee ID, and then the
Annual Salary, type awk '{print $3, $1, $4}' employees.dat, and
then press LntIr. See ligure 11-3. 1he Iast Name, Lmployee ID, and then
the Annual Salary ot all input lines are displayed respectively.
6. 1o embed text vithin the print statement tor use in displaying a user-triendly
descriptive statement, type awk '{print "Employee " $2 " earns
"$4 ". "}' employees.dat, and then press LntIr. See ligure 11-4. 1he
lirst Name and Annual Salary, along vith descriptive text, are displayed tor
all lines.
8MT
11
7. 1o place a tab betveen the lirst Name and the Annual Salary tields tor use in
displaying additional space betveen the tields and text, type awk '{print
"Employee " $2 "\t earns " $4 "."}' employees.dat, and then
press LntIr. See ligure 11-4. 1he lirst Name and Annual Salary along vith
descriptive text are displayed.
8. 1o place a nev line betveen the lirst Name and the Salary tields and text,
type awk '{print "Employee " $2 "\n earns " $4 "."}'
employees.dat, and then press LntIr. See ligure 11-4. 1he lirst Name is
displayed on one line, and the Annual Salary is displayed on the next line tor
each line ot input.
9. Close your vindov, and then log out.
*MKuVe 11- 9se o awkprint sLaLemenL Lo cusLomMze ouLpuL
SLep 7: noLice LhaL Lhere
is a Lab beLween Lhe
FirsL Name and Lhe
LexL "earns"
*MKuVe 11-3 9se o awkprint sLaLemenLs
SLep 2: because a column
represenLs a ield and a line
represenLs a record, you
can say LhaL all ields o all
records are displayed wiLh
Lhe use o print $0
38 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
LeaVRMRK AbouX E[O 4VoKVam )xecuXMoR aRH CommaRH SXVucXuVe 39
8Le MJ SXaXemeRX
1he if action statement in awk logically vorks the same vay as in the shell. Hovever,
its implementation ditters slightly.You use the if decision structure to display lines ot input
vhen certain conditions are matched. lor example, you have a Sales tile, and you vant to
display the name ot all sales people vho earned over s230,000 in commissions last year.
1o do so you use the if statement. Next you vill use this decision structure in awk.You
vill use the employees.dat data tile that you created earlier.
1o usI thI if actMon statInInt Mn awk
1. Iog in to the Iinux system as a user, open a 1erminal emulation vindov, and
then change to the $HOME/bin directory.
2. 1o use the if statement to display the lirst Name, Iast Name, and Salary
vhen the Lmployee ID equals 3, type awk '{if {$1 == 3} print
$2, $3, $4}' employees.dat, and then press LntIr. Note you must
surround the condition statement {$l == 3| vith parentheses. Also, tvo
equal signs represent equal to in awk. See ligure 11-3. 1he record tor enny
Patel is displayed.
3. 1o display the lirst Name, Iast Name, and Salary vhen the Lmployee ID
equals 1 or 4, type awk '{if {$1 == 1 [[ $1 == 4} print $2,
$3, $4}' employees.dat, and then press LntIr. See ligure 11-3. 1he
records tor Marge Smith and Iin Iui are displayed.
4. 1o display the lirst Name, Iast Name, and Salary vhen Salary is less than or
equal to s42,000, type awk '{if {$4 <= 42000} print $2, $3,
$4}' employees.dat, and then press LntIr. See ligure 11-3. 1he record
tor Vu Iung is displayed.
3. 1o display the lirst Name, Iast Name, and Salary vhen the Iast Name contains
the letters Iiu, type awk '{if {$3 - "Liu"} print $2, $3, $4}'
employees.dat, and then press LntIr. See ligure 11-3.1he record tor Iin
Iiu is displayed.
6. 1o display a message tor employees vith a salary over or under a specitic
amount, in this case s30,000, you can also use an else clause vith the if
statement. 1ype awk '{if {$4 > 50000} print $2 "\t Over
11
$50,000", else print $2 "\t Under $50,000" }'
employees.dat, and then press LntIr. See ligure 11-3. Lach input line
is displayed vith an appropriate message depending on vhether their
salary is over or under the amount.
7. Close your vindov, and then log out.
+)88IN+ (A8A IN8O 8H) %;/ 46O+6AM
In general, inputting data makes your awk statements more tlexible because you can con-
trol the data that awk uses.1he awk program allovs you to input data using tvo ditterent
styles.1hey are as tollovs
Passing data at the command line
Prompting tor user input ot data
4assMRK DaXa aX XLe CommaRH LMRe
1he awk program allovs you to assign values to variable names at the command line.1he
benetit ot this is that these values can then be used by awk tor displaying, calculating, or
comparing data, tor example.Variable assignment is much like using positional parameters
tor the shell and makes awk very tlexible because it can accept any data tor manipulation.
Here`s the general syntax
awk ~v var1ao1e~name=va1ue
*MKuVe 11-5 9se o awk and Lhe if sLaLemenL used Lo deLermMne employee MnormaLMon
SLep 3: noLe Lhe use o ]]
Lo represenL Lhe OR loical
operaLor
SLep 5: noLe Lhe use o Lhe
Lilde symbol (~) represenLs
"conLains" Lo awk
0 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
+eXXMRK DaXa MRXo XLe E[O 4VoKVam 1
1he ~v option is required and is used to indicate the var1ao1e~name and va1ue
assignment.You can assign multiple values but you must use separate ~v options tor each
pair. lor instance, it you vant to assign product to be equal to 30 and price equal to
100, then you must enter this partial code, awk ~v product=50 ~v price=l00, at
the command line.You could then use these variable names vithin the awk statements.
Next you vill learn hov to make variable assignments at the command line.
1o usI varMablI assMgnnInts Mn awk
1. Iog in to the Iinux system as a user, open a 1erminal emulation vindov, and
then change to the $HOME/bin directory.
2. 1o display a message that displays employee names vith a salary over or
under a determined amount specitied at the command line, type
awk ~v Amt=60000 '{if {$4 >=Amt} print $2 "\t Over/Egual
to", else print $2 "\t Under "}' employees.dat, and then press
LntIr. See ligure 11-6. Lach input line ot the employees.dat data tile is dis-
played vith an appropriate message vhether the salary tor the employee is
over or under the specitied amount.
3. 1o assign tvo variables at the command line and compare their values to the
contents ot the employees.dat tile, type awk ~v Amt=60000 ~v
Name=Marge '{if {$4 >= Amt && $2 - Name} print $2 "\t You
are eligible to receive the executive bonus. ", else print
$2 "\t You are eligible to receive the administrative
bonus. " }' employees.dat, and then press LntIr. Note, the use ot the
tilde tor contains. It the second tield, $2, contains the Name Marge, then
the text You are eligible to receive the executive bonus. is displayed. See
ligure 11-6. Lach input line ot the employees.dat tile is displayed vith an
appropriate message based on hov the salary evaluates against the conditions
established in the if and else statements.
4. 1o create a report vith a report header and tooter combined vith a variable
assignment, type awk ~v Amt=60000 ~v Name=Marge 'BEGIN
{print "Salaries Over/Egual or Under " Amt} {if {$4 >=
Amt} print $2 "\t Over/Egual", else print $2 "\t Under " }
END {print "*** Report End ***"}' employees.dat, and then
press LntIr. See ligure 11-6. 1he header is displayed, tolloved by the records,
then the tooter.
3. Close your vindov, and then log out.
11
4VomTXMRK foV UseV IRTuX of DaXa
You can also prompt tor user input as you can vith the read statement in the shell.1he
awk statement that accomplishes this is the getline statement. 1his translates to get
a line ot text trom standard inputthe keyboard.You use the getline statement vhen
you vant to prompt a user tor input. 1he prompt method allovs you to customize a
user-triendly prompt tor a user instead ot having the user enter positional parameters as
vith the previous method. Here`s the general torm
getline var1ao1e~name < f11e
1his is vhere var1ao1e~name is the name ot a variable that contains the data that the
user enters. 1he less-than symbol is used to redirect data trom a tile. 1he tolloving line
ot code shovs hov to place data contents entered by a user into a variable named pay.
getline pay < "~"
Note the use ot < "~" means to redirect trom standard input, vhich as you recall is
your keyboard. Next you vill create a script that prompts tor user input tor an Lmployee
ID. As awk processes each line ot input, it compares tield 1 vith the Lmployee ID that is
entered. It vhat is entered and the Lmployee ID are equal, then the lirst Name, Iast
Name, and Annual Salary are displayed. Note there is a report tooter that is also displayed.
1o usI thI pronpt for usIr Mnput Mn awk
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named avkpronpt in your $HOME/bin directory.
*MKuVe 11-6 9se o varMable assMKnmenLs
SLep 3: alLernaLively, you
could use $2==Name, in
Lhis example
2 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
+eXXMRK DaXa MRXo XLe E[O 4VoKVam 3
3. Insert the tolloving lines ot code to set up the prompt, create the condition
to be evaluated, and display a report tooter. Notice the use ot the printf
command. In awk, this command is similar to print, but allovs you to
tormat the text being printed. In this case, it serves to keep the cursor on
the same line as the prompt Lnter ID. It you had used print, the cursor
vould appear on the line belov the prompt Lnter ID. Lsing printf in
this case, is more user-triendly.
BEGIN { printf "Enter ID: ", getline ID < "-" }
{
if {$1 == ID}
{
print "Employee Data"
print $2, $3, $4
}
}
END { print " *** Report End *** " }
4. Save the script, close the editor, and then make the script executable.
3. 1ype awk -f awkprompt employees.dat to execute the script, and then
press LntIr.
6. Lnter 3 as input vhen prompted to enter ID, and then press LntIr. See
ligure 11-7. 1he lirst Name, Iast Name, and Salary tields tor employee
enny Patel are displayed.
7. Perun the script. 1his time enter 1 as input vhen prompted, and then press
LntIr. See ligure 11-7. 1he lirst Name, Iast Name, and Salary tields tor
employee Marge Smith are displayed.
8. Lxecute the script again. 1his time enter as input vhen prompted, and
then press LntIr. See ligure 11-7. Because there is no employee vith this
Lmployee ID, no record is displayed.
9. Close your vindov, and then log out.
11
9SIN+ E[O 7C6I48S
As you have seen in the previous exercise, you can place awk commands in a script tile
and then run awk vith the ~f option to process the commands vithin the script
tile.1he main reason you place awk commands in a script tile is to ensure programmer
readability tor a large number ot commands in need ot processing. ust like a shell script,
the commands vithin an awk script can be indented or commented to make them
easier to viev and understand. Any awk command can be placed vithin a tile and used
as an awk script.
Reer Lo Lhe man paes on awk or addiLional commands.
It you do create an awk script, you cannot run the script in the shell vithout explicitly
using awk. 1his is because the awk statements are not executable by the shell. Here is
the general syntax torm tor using an awk script
awk ~f scr1t~name f11e
1he ~f option means that you are giving awk a script, specitied by scr1t~name, that
contains awk commands. 1he f11e specitication is a data tile used as input into awk.
When creating awk script tiles, you use the # character vhen commenting.You can also
place multiple statements on one line, but you need to separate each statement vith the
semicolon metacharacter, ,.
8MT
*MKuVe 11-7 1he awkprompL scrMpL and MLs execuLMon
CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
UsMRK E[O ScVMTXs 5
Next you vill create a script named avkscript1 vhich uses the employees.dat data tile
to create an output tile named LmpMon.dat and a report that is displayed on the screen.
1he output tile, LmpMon.dat, is created to shov you hov creating tiles is done in awk.
1his nev tile could in turn be processed by yet a ditterent awk script tor some other
purposetor example, to give employees a raise based on their monthly salary. Also
introduced is the use ot an awk builtin variable named NR. 1his variable represents the
total number ot input records awk has processed. It you place NR vithin the END pattern,
it can be used to display the total number ot records vithin the tile, thus acting as a record
counter. linally, an awk builtin numeric tunction, int{exress1on|, is used to turn
the monthly salary into an integer value. 1he employee`s monthly salary is calculated
using the value tor Annual Salary.
1o crIatI an awk scrMpt
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named avkscrMpt1 in your $HOME/bin directory.
3. Insert the tolloving lines ot code to display the heading line and begin the
awk script
BEGIN { print "ID \t Name \t\t Monthly Pay" }
{
4. Insert the tolloving line ot code to calculate the monthly salary as an integer
MonthlySal=int{{$4 / 12}}
3. Insert the tolloving line ot code to display the Lmployee ID, the Iast Name,
a comma, the lirst Name, and the Monthly Pay ot an employee respectively
print $1 "\t" $3 ",\t" $2 "\t" MonthlySal
6. Insert the tolloving line ot code to redirect the Lmployee ID, the lirst
Name, Iast Name, and the Monthly Pay to a tile named LmpMon.dat. Note
the use ot the redirection symbol to redirect the output to the tile
print $1, $2, $3, MonthlySal > "EmpMon.dat"
7. Insert the tolloving lines to display a tooter line that is displayed atter all
input lines, in this case records, are processed. 1he number ot employees is
displayed using the awk NR builtin variable
}
END { print " " ,print "Number of employees: " NR,
print "*** End of Report ***" }
8. Save the script, and then close the editor.
9. Make the script executable, and then execute the script. 1ype awk -f
awkscript1 employees.dat to execute the script, and then press LntIr.
11
1he script runs and displays the report on the screen. ligure 11-8 shovs the
execution and the resulting report.
10. Display the contents ot the LmpMon.dat tile. ligure 11-9 shovs the contents ot
this tile. Notice the tourth tield is the Monthly Pay instead ot the Annual Salary.
11. Close your vindov, and then log out.
*MKuVe 11-9 1he conLenLs o Lhe LmpNondaL Mle also creaLed by awkscrMpL1
*MKuVe 11-8 1he awkscrMpL1 awk scrMpL processMnK employee records Mn Lhe employee
daLa Mle
SLep 9: Lhe ile,
LmpNon.daL, is also
creaLed, buL you need Lo
display iLs conLenLs Lo see
Lhe daLa
6 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
UsMRK E[O ScVMTXs 7
CVeaXMRK SysXem AHmMRMsXVaXMoR UXMlMXMes UsMRK E[O
One benetit ot awk is that you can use it to customize the output ot other Iinux com-
mands, thus alloving you to create scripts that suit your ovn needs. 1o better under-
stand this concept, take a look at a tev awk scripts that modity the output ot Iinux
commands. Note that the output ot these Iinux commands is piped to the awk command
tor turther processing.
You are already tamiliar vith the who command and its output. Suppose you vant to
customize the output to display text indicating the username and vhen the user logged
in. Because the who command displays text in columns, you could reterence these
columns by their position using the positional parameters $l, $2, and so on. 1o display
usernames and the times they logged in, you use $l and $5, respectively.You vrite the
script statement as tollovs
who ] awk '{print $l, $5}'
Say you vant to display the usernames, the month, and date.You use positions $l, $3,
and $4 ot the who output listing. 1he next statement displays these columns along vith
a tooter line indicating the number ot users that are currently logged in using NR.
who ] awk '{print $l, $3, $4} END {print "There are " NR "
users logged on now."}'
It you vant to see one column listed betore another, you could even alter the order in
vhich the columns are displayed. Suppose your manager vants to see the output ot
the who command moditied so that a header line is displayed tolloved by the day ot the
month, then the month name, and tinally the user name tor each user logged in. You
vrite this script statement as tollovs
who ] awk 'BEGIN {print "Date \t Username"} {print $4, $3,
"\t", $l}'
ligure 11-10 shovs the statements and output tor these three requirements.
Iook at another example.1he Iinux command df shovs you disk space usage and the
availability ot various tile systems. A fMlI s]stIn is a partition, or portion, ot a hard disk
drive. Iook at ligure 11-11.Atter the df command is executed, the tile system intormation
is shovn in six columns ot data.1he tirst column represents the tile system name.1he titth
column displays the usage as a percent. Say you don`t vant to see all ot the output ot
the df command. Perhaps you only vant to see the tile system name and the percent
used. In this case, you can use awk to display the tile system name as $l and the percent
used as $5. Note the awk if statement is used to eliminate the tile system labeled none
trom the listing.1he use ot the {if {$l !- "none"| { print $l, $5}} statement
is to display the tirst and titth column oni it the tirst column does not contain the text
none in ligure 11-11.
11
You can also use the awk system{command| tunction to run or call an operating system
command, specitied by command. 1he benetit ot using the system{command| tunction
is that you can incorporate Iinux commands vithin an awk script. Once the command
completes, control returns to the next awk command, vhich in the example shovn in
ligure 11-11 is the if statement. In this script the system{"date +%D"| command is
used to display the current date in MMDDYY tormat.
*MKuVe 11-11 1he df command, Lhe awkd scrMpL, and Lhe ouLpuL rom execuLMnK awkd
*MKuVe 11-10 1he ouLpuL o Lhe who command usMnK Lhe prevMous Lhree
who]awk sLaLemenLs
8 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
WoVkMRK wMXL XLe HMEPSK CommaRH 9
Iook at one more example.As you knov, the ls ~l command displays output in columns.
Say you vant to display the tile type, permissions, and the tilename, plus shov a total count
ot the number ot directories or tiles in the list.1o do so you enter this statement
ls ~l ] awk '{print $1, $9} END {print "Number of entries: " NR ~ 1}'
Both tile type and permissions are located in $l. Note that the END {print
"Number of entries: " NR ~ l}' statement is displayed last.1he use ot NR ~ l
displays the total number ot directories and tiles in the listing. It you don`t subtract one
trom NR, then awk includes the tirst line that displays total in NR. ligure 11-12 shovs
the awk script named avkls and the output trom executing it.1he output ot the ls ~l
command is not shovn.
;O6/IN+ WI8H 8H) HMEPSK 'OMMAND
1he dialog command is extremely usetul tor creating dialog boxes vithin scripts. A
dMalog bo is a vindov that appears on the screen and establishes user interaction.
Dialog boxes allov you to make an extremely user-triendly, screen-oriented script. lor
example, you can create dialog boxes to list shell commands that users can execute by
pressing a specitic number or letter on the keyboard. Lsers could then use this dialog
box to execute commands tor themselves instead ot having to enter the commands
directly into the shell. Lsing dialog boxes reduces the possibility ot users encountering
errors vhen entering shell commands. 1he general syntax ot the dialog command is
dialog common~ot1ons oox~ot1ons
*MKuVe 11-12 1he awkls scrMpL and MLs ouLpuL
11
1his is vhere common~ot1ons are options that apply to all boxes, such as specitying a
title or redirecting standard output. 1he oox~ot1ons options are the types ot dialog
boxes you can use along vith their ovn specitic options. Iook at 1able 11-3 tor a listing
ot the common~ot1ons and their purposes. Note that the third column shovs only a
partial example.You also need to add the correct dialog box statements to the dialog
command tor the commands to vork. In other vords, you cannot simply use the common
options vithout using a dialog box. Hovever, you can use a dialog box vithout using a
common option.
lor nov, just be avare ot these common options that apply to all dialog boxes. In a later
section, you vill use these options along vith dialog boxes.
8Le MeRu DMaloK &ox
Several dialog box types exist, each vith its ovn purpose.Although each dialog box type
can have ditterent parameters, there are certain parameters that are common to all dialog
boxes. 1he common parameters are as tollovs
1ext1he contents or caption ot the dialog box
Height1he height in character positions ot the dialog box
Width1he vidth in character positions ot the dialog box
CommoR OTXMoR DescVMTXMoR 4aVXMal )xamTle (VequMVes
a HMaloK box)
~~backtitleoackt1t1e Speciies Lhe LiLle LhaL is displayed dialog~~backtitle
aL Lhe Lop o Lhe screen "InventoryScreen"
~~beginyx Speciies Lhe posiLion o Lhe upper- dialog~~begin34
leL corner o Lhe dialo box on
Lhe screen
~~clear Clears Lhe dialo screen dialog~~clear
~~shadow Draws a shadow Lo Lhe rihL and dialog~~shadow
boLLom o each dialo box
~~sleepseconds ALer processin a dialo box, dialog~~sleep15
delays processin or Lhe amounL
o seconds speciied
~~stderr DirecLs ouLpuL Lo sLandard error; dialog~~stderr
Lhis is Lhe deaulL
~~stdout DirecLs ouLpuL Lo sLandard ouLpuL dialog~~stdout
~~timeoutseconds 1imes ouL i Lhere is no user dialog~~timeout10
response or Lhe amounL o
seconds speciied
~~titlet1t1e Speciies Lhe LiLle LhaL appears aL dialog~~title
Lhe Lop o Lhe dialo box "AddRecord Screen"
8able 11-3 A ew o Lhe common opLMons used by Lhe dialog command
50 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
WoVkMRK wMXL XLe HMEPSK CommaRH 51
Although quite a tev dialog boxes exist, not all ot them vill be discussed in detail in
this chapter. 1he menu dialog box is very practical because it allovs you to present the
user vith a list ot choices in the torm ot a menu. It takes the tolloving general torm
dialog ~~menu text he1ght w1dth menu~he1ght tag1 1tem1
tag2 1tem2...
1he tirst three parameters, text, he1ght, and w1dth, have already been mentioned.
1he menu~he1ght is the height ot the menu vithin the menu dialog box. A menu
entry is composed ot a tag and an 1tem pair. 1he tag is a unique entry distinguishing
the item trom other items in the menu. It the height ot the menu is not large enough to
display all ot the menu choices, then users can scroll up and dovn vithin the menu items
or they can select the tag representing the item. 1he user selects an item by highlighting
the tag associated vith it.
Here is an example to help you understand hov this vorks. In the tolloving code segment,
the menu dialog box is used to display a menu. 1he text is set to display Menu Iist, the
dialog box`s height is set to 13 character positions, the vidth is set to 60 character positions,
and the menu height is set to tvo character positions. 1here are tvo tagitem pairs vhich
allov users to choose tag 1 tor Item 1 or to choose tag 2 tor Item 2. Pight nov, you
are just learning about the syntax ot this command. Iater, you vill add additional code to
make your menu more tunctional.
dialog ~~menu "Menu List" l5 60 2 l "Item l" 2 "Item 2"
Note that the tag a user enters is vritten to standard error. So, it users enter 1, tor
selection 1, the number 1 is vritten to standard error. It they enter 2, the number 2 is
vritten to standard error instead. Lsing this knovledge, a script can be created to pertorm
a task in the event users make one choice and another task it users make a ditterent choice.
ligure 11-13 shovs the menu dialog box that is displayed as a result ot entering the
previous command. Lsers can press 1ab to move betveen the menu items. 1hey can
press the OK and Cancel buttons that appear on the screen as vell. Note it users press
the OK button, then the menu dialog box exits vith a status ot zero, and it users press
the Cancel button, then the menu dialog box exits vith an exit status ot one. 1his is
true tor most ot the other dialog boxes that exist as vell. Lsers can select a menu item
by pressing the number to the lett ot the item they vant. Or, users can press the up and
dovn arrovs to scroll up and dovn vithin the menu list, and then press Lnter to make
a selection.
11
MoHMfyMRK a MeRu DMaloK &ox
Next, you change a tev things so you can see vhat happens to the dialog box. lirst, tvo
common options are added, the ~~title and ~~backtitle options. Also, the menu
height is changed trom 2 to 1, so you can see hov scrolling vithin the menu vorks. Here
is the menu dialog box vith revisions to the code
dialog --title "Main Menu List" ~~backtitle "THE MENU" ~~
menu "Menu List"l5 60 l l "Item l" 2 "Item 2"
ligure 11-14 shovs the resulting menu dialog box ot the previous statement.You can use
the common options to modity the output appearing on your screen. 1his allovs you to
customize all dialog boxes tor your users. Notice the changes. A backtitle appears in the
1erminal emulation vindov, and a title appears at the top ot the menu dialog box. Also,
the menu height has been changed to 1.1his demonstrates vhat happens vhen you have
more tagitem pairs than alloved tor by the menu height. Also, in ligure 11-14, a little
green V {+| appears belov the menu indicating there are more options trom vhich
to choose. 1o go to Item 2, you scroll dovn using the dovn arrov key. It you do this,
then ` {+| appears indicating you need to scroll up using the up arrov key to go back
to Item 1.You can scroll up and dovn as needed to see any choice in the list.
Next you vill create a practical system administration script using a menu dialog box
that allovs users to press the number 1 tor the ls command to execute and the
number 2 tor the who command to execute. It users press Cancel, the exit status ot
the menu dialog box is one. It they press OK, the exit status is zero. 1he exit status is
tested so that it the user decides to cancel the dialog box, the script exits instead ot
running the commands.
*MKuVe 11-13 A menu dMaloK box
lLems
1he menu selecLion area;
Lhis is aecLed by Lhe
menu heihL opLion
1as
Dialo box heihL
Nenu heihL
Dialo box widLh
52 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
WoVkMRK wMXL XLe HMEPSK CommaRH 53
Once the user chooses an item, its corresponding tag is redirected to standard error.
Standard error is then redirected to a tile so you can keep track ot the choices and later
test them. Hovever, you only vant to keep the choice that vas made tor the duration
ot the script, so the tile is removed attervards. You use the shell`s special parameter, $,
vhich expands to the PID ot the current shell to name the tile. 1he name ot the tile is
$HOME/menu.$$. By using $$, you are guaranteed to get a unique tilename because the
PID is ditterent each time the shell is run. 1his vay, you von`t accidentally name it a
tilename used by another script. 1his is a standard vay to name tiles that contain
temporary data.
You also use command substitution to save the contents ot the temporary tile to a variable.
1he shell`s case statement is used to establish the value ot the variable. It the variable is
a 1, then the user selected item 1, and this indicates he or she vants the ls command
to run. It the variable is a 2, then the user selected item 2, and this indicates he or she
vants the who command to run.
1o crIatI a nInu usMng thI dialog connand
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named dMalognInuA in your $HOME/bin directory.
3. Insert the tolloving line ot code to display the menu dialog box and
redirect the tag entered by the user trom standard error to a temporary tile
named $HOME/menu.$$
dialog --
menu "Menu List" 10 60 5 1 pwd 2 who 2>$HOME/menu.$$
*MKuVe 11-1 A menu dMaloK box wMLh modMMcaLMons
Dialo box LiLle
8ecause Lhe menu heihL
was chaned Lo 1, only
one La/iLem pair is lisLed.
8ecause Lhere is anoLher
La/iLem pair, Lhen you use
Lhe Up and Down arrow
keys Lo scroll beLween
Lhe iLems
8ackLiLle common opLion
1iLle common opLion
11
4. Insert the tolloving line ot code to maintain the exit status ot the dialog
~~menu command
Status=$?
3. Insert the tolloving lines ot code to create the decision structure to test
vhether OK or Cancel has been entered by the user
if $Status ~eg 0 ]] # OK was pressed.
then
6. Insert the tolloving line ot code to retrieve the tag trom the tile and store it
in a variable named ans
ans=`cat $HOME/menu.$$`
7. Insert the tolloving lines ot code to test tor the possible choices and execute
the appropriate command
case $ans in
"1"} pwd
,,
"2"} who
,,
esac
8. Insert the tolloving line ot code to remove the temporary tile
rm $HOME/menu.$$
9. Insert the tolloving line ot code to test vhether Cancel has been entered
else # Cancel was pressed.
10. Insert the tolloving line ot code to display an exit message because Cancel
has been pressed
echo "Exiting..."
11. Insert the tolloving line ot code to terminate the decision structure
fi
12. Save the script, and then close the editor.
Make the script executable, execute the script, and then select choice 1 to
run the pwd command. See ligure 11-13. 1he output ot the pwd command
appears on the screen. Note the output could appear anyvhere on the screen.
1o clear Lhe screen o Lhe menu dialo box, you could inserL Lhe clear
command immediaLely prior Lo Lhe case sLaLemenL.
13. Perun the script, and then select choice 2 to run the who command. 1he
output ot the who command appears on the screen.
8MT
5 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
WoVkMRK wMXL XLe HMEPSK CommaRH 55
14. Perun the script, and then press CancIl. 1he message Lxiting. appears on
the screen.
13. Close your vindov, and then log out.
OXLeV DMaloK &oxes SuTToVXeH by XLe HMEPSK CommaRH
1he dialog command supports a number ot other dialog boxes. 1hey vork similarly
to the menu dialog box. A tev are listed in 1able 11-4.
DMaloK &ox DescVMTXMoR )xamTle
~~checklisttext Similar Lo Lhe menu dialo box; insLead dialog~~checklist
he1ght w1dth o choosin one enLry rom Lhe lisL, a "CheckList"
11st~he1ght tag user can choose rom several iLems; you 106051pwd2
1tem status can also seL Lhe sLaLus o a La/iLem whooff
pair Lo eiLher "on" or "o"
~~fselectpath Allows you Lo display a LexL-orienLed dialog~~fselect
he1ght w1dth window showin direcLories and iles $HOME1050
beinnin aL a speciied paLh
~~inputboxtext Allows you Lo prompL users or inpuL; dialog~~inputbox
he1ght w1dth users can enLer any characLers or "Entervalueto
1n1t1a1~va1ue numbers; you can seL an iniLial value display"1050
usin Lhe 1n1t1a1~va1ue opLion
8able 11- A ew o Lhe dMaloK boxes used by Lhe dialog command
*MKuVe 11-15 9sMnK a menu scrMpL Mn conNuncLMon wMLh LMnux operaLMnK sysLem commands
1he resulL o selecLin La
number 1; Lhe presenL, or
currenL, workin direcLory
is displayed
11
-M4L)M)N8IN+ 1UL8I4L) (IALO+ &OX)S ;I8HIN A 7C6I48
Nov that you have seen some ot the dialog commands, it is important to understand
hov to combine multiple commands vithin a single script. Suppose you vork tor
Pockets Ped Glare Inc., a manutacturer ot model rockets. 1hey use the Iinux operating
system, and the manager vants you to create a script that displays the directories and tiles
in a user`s home directory, allovs the user to select a tile, and then display the contents
ot the tile. 1o complete this request, you need to use several dialog commands.
8Le *Mle SelecXMoR, 8exX &ox, aRH MessaKe DMaloK &oxes
Next you vill create a script that uses the tile selection dialog box, using the
dialog ~~fselect command, to display a list ot directories and tiles in the user`s home
directory. It the user selects a tile and then presses OK, a text box dialog box using the
dialog ~~textbox command is used to display the contents ot a tile. Iike the menu
dialog box, standard error is redirected to a tile, and then the contents ot that tile are held
DMaloK &ox DescVMTXMoR )xamTle
~~msgboxtext Allows you Lo display LexL ollowed dialog~~msgbox
he1ght w1dth by an OK buLLon; users can read Lhe "Filedeleted"1050
messae, and Lhen press OK. 1his is
useul or displayin inormaLional
messaes Lo users.
~~passwordbox Allows you Lo prompL a user or a dialog~~passwordbox
text he1ght password; Lhe password is noL "Enterpassword"960
w1dth 1n1t1a1~ displayed as Lhe user enLers iL on
va1ue Lhe screen
~~radiolisttext Similar Lo a menu dialo box; however, dialog~~radiolist
he1ght w1dth you can indicaLe which enLry is selecLed "RadioList"
11st~he1ght tag by seLLin Lhe sLaLus Lo eiLher "on" or 106051
1tem status "o" or a La/iLem. 1he user can selecL pwd2onwhooff
only one iLem. On exiL, Lhe La is senL Lo
sLandard error.
~~textboxf11e Allows you Lo display Lhe conLenLs o a dialog~~textbox
he1ght w1dth ile as a simple LexL viewer file4.txt1550
~~yesnotext Allows Lhe user Lo selecL rom eiLher a dialog~~yesno
he1ght w1dth "Yes" buLLon or a "No" buLLon; Lhe LexL "Entervalue"750
displays Lhe messae Lo which Lhe user
needs Lo respond. 1his box is used or
prompLin a user or responses LhaL can
only be answered in eiLher Lhe airmaLive
or neaLive
8able 11- A ew o Lhe dMaloK boxes used by Lhe dialog command (conLMnued)
56 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
ImTlemeRXMRK MulXMTle DMaloK &oxes WMXLMR a ScVMTX 57
in a variable named tilename. Also, a tunction named msg is used to display a message box
and clear the screen vhen the user presses Cancel or LXI1.A tunction is used here because
the same steps are pertormed in several places vithin the script.
1o crIatI a scrMpt that sIlIcts fMlIs usMng nultMplI dialog boIs
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named dMalogfMlIvMIv in your $HOME/bin directory.
3. Insert the tolloving lines ot code to create the message box tunction and
clear the screen
function msg {}
{
dialog --msgbox "Exiting" 5 40
clear
}
4. Insert the tolloving line ot code to display the tile selection dialog box and
redirect the tilename chosen to a temporary tile
dialog --fselect $HOME/bin/dialogmenuA 5 50 2>$HOME/fs.$$
$HOME/bin/dialogmenuA (Lhis is used in Lhe previous exercise so iL should
be presenL) is Lhe ile LhaL appears by deaulL unless Lhe user chooses anoLher
ilename. l Lhe user presses OK, Lhen Lhis is Lhe ile LhaL is selecLed. 1his is
an example o seLLin a deaulL value. 1he name o Lhe ile is senL Lo sLandard
error. ln Lhis example, sLandard error is redirecLed Lo a ile named
$HOME/fs.$$. lL conLains Lhe name o Lhe ile Lhe user selecLed.
3. Insert the tolloving lines ot code to keep the exit status and test it. It the
user presses OK, then the exit status is zero. It the user presses Cancel, the
exit status is one.
Status=$?
if $Status -eg 0 ]]
then
6. Insert the tolloving line ot code so the variable named tilename contains the
name ot the tile selected
filename=`cat $HOME/fs.$$`
7. Insert the tolloving line ot code to display the tile selected using $filename
dialog --textbox $filename 15 50
8. Insert the tolloving line ot code to call the tunction named msg
msg
11
9. Insert the tolloving line ot code to remove the temporary tile
rm $HOME/fs.$$
10. Insert the tolloving lines ot code tor the remaining if condition. Again, the
steps here are done it the user presses Cancel in the dialog ~~fselect
dialog box
else
msg
fi
11. Save the script, and then close the editor.
12. Make the script executable, and then execute the script. See ligure 11-16. 1he
initial tile selection dialog box appears. Depending upon the directories and
tiles vithin your current directory, your screen may ditter trom ligure 11-16.
13. Press OK. See ligure 11-17. 1he contents ot the dialogmenuA script tile are
displayed in the text box dialog box.You can use the up and dovn arrov
keys or page up and page dovn keys to scroll through the tile.
14. Scroll up and dovn vithin the tile. When you have vieved everything, press
the LI1 button to exit the textbox dialog box. See ligure 11-18. 1he tinal
message dialog box screen appears and displays the text Lxiting.
13. Press OK to close the last dialog box and exit the script.
*MKuVe 11-16 1he Mle selecLMon dMaloK box
Files window pane
1he ile selecLion box
conLains Lhe selecLed ile
1he OK and Cancel
buLLons; noLe Lhe deaulL
selecLion is Lhe OK buLLon
DirecLories window pane
58 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
ImTlemeRXMRK MulXMTle DMaloK &oxes WMXLMR a ScVMTX 59
16. 1o get tamiliar vith the tile selection dialog box, rerun the script. When the
tile selection dialog box appears, press 1ab as many times as necessary to move
through the Directories vindov pane on the lett side, the liles vindov pane
on the right side, the tile selection box in the bottom pane, and the OK and
Cancel buttons.
17. 1o select a nev tile to viev, press 1ab until the cursor blinks in the liles
pane. Press the up and dovn arrov keys to locate a tile ot your choosing.
1he tile you choose is highlighted in blue.
18. 1o select the highlighted tile, press the spacIbar. 1he path ot the tile appears
in the tile selection box.
19. Press the OK button to display the contents ot the tile. 1he nevly selected
tile is displayed.
20. Press the LI1 button to close the text box dialog box. 1he message dialog
box appears displaying the text Lxiting on the screen.
21. Press the OK button to exit. 1he screen clears and the script terminates.
22. Close your vindov, and then log out.
*MKuVe 11-17 1he LexL box dMaloK box dMsplayMnK Lhe conLenLs o Lhe Mle
NoLice Lhe 79%; Lhis is Lhe
percenLae o Lhe ile
bein shown Lo you
11
UsMRK XLe CLecklMsX, MsK, aRH CaleRHaV DMaloK &oxes
It you vant to allov your users to select multiple choices, you need to understand hov
to implement the checklist dialog box. Next you vill use a checklist dialog box that
allovs the user to select trom one to three choices.When the user presses OK, the script
executes the commands tor the choices selected. 1he choices are sent to standard error
and standard error is redirected to checkmenu.ss. Because the user can select any combi-
nation ot 1, 2 or 3, the grep statement is used to search tor the existence ot a 1, 2, or 3
in the checkmenu.ss tile. It a 1 exists, then the user selected item 1, and the code tor
item 1 executes. 1he same logic exists tor the other tvo options. It a user selects any
combination, then all the items selected execute.
1o crIatI a scrMpt that usIs thI chIcklMst dMalog bo
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named dMalogchIckA in your $HOME/bin directory.
3. Insert the tolloving lines ot code to create the checklist dialog box. 1he tirst
option, Display Message, is set to on, indicating it is the detault. It the user
presses OK vithout selecting an option, then the code tor item 1 executes.
Notice standard error is redirected to a tile.
dialog --checklist "Checklist" 10 30 5 1 "Display
Message" on 2 "DisplayFile" off 3 "Display
Calendar" off 2>$HOME/checkmenu.$$
*MKuVe 11-18 1he messaKe dMaloK box
60 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
ImTlemeRXMRK MulXMTle DMaloK &oxes WMXLMR a ScVMTX 61
4. Insert the tolloving lines ot code to search tor the value ot 1 in the
checkmenu.ss tile. It the user selects 1 in the previous statement, a 1 is
redirected to checkmenu.ss.
grep 1 $HOME/checkmenu.$$ > /dev/null
3. It a 1 is tound in the tile, the grep command completes vith an exit status
ot zero. Insert the tolloving lines ot code to test tor a successtul exit status. It
the exit status equals zero, then display a message in a msg box dialog box.
1he msg box displays the text Hello on the screen.
if $? -eg 0 ]]
then
dialog --backtitle "Message Box" --msgbox "Hello" 5 10
fi
6. Insert the tolloving lines ot code to handle selection 2. Notice this is very similar
to the previous tev lines tor handling selection 1. It the user selected item 2, then
a text box dialog box is displayed.1he text box displays the contents ot a tile.
grep 2 $HOME/checkmenu.$$ > /dev/null
if $? -eg 0 ]]
then
dialog --backtitle "Text Box" --textbox
$HOME/bin/dialogmenuA10 30
fi
7. Insert the tolloving lines ot code to handle selection 3. Again, this is very
similar to the previous tev lines tor handling selection 1 and 2 above. It the
user selected item 3, then a calendar dialog box is displayed.
grep 3 $HOME/checkmenu.$$ > /dev/null
if $? -eg 0 ]]
then
dialog --backtitle "Calendar" --calendar
"Current Month" 5 30
fi
8. Insert the tolloving lines ot code to remove the temporary tile named
checkmenu.ss and clear the screen
rm $HOME/checkmenu.$$
clear
9. Save the script, and then close the editor.
10. Make the script executable, and then execute the script. See ligure 11-19.
1he checklist dialog box displays.
11. 1o display the calendar, use the dovn arrov to move your cursor to item 3.
When item 3 is highlighted, press the spacIbar to select it. An X appears
to the lett ot item 3. At this point, the tirst and third items are selected.
12. Press LntIr. Because item 1 has been selected, the message Hello appears
on the screen.
11
13. Press the OK button. Because item 3 has also been selected, the current
calendar appears on the screen. See ligure 11-20.
14. Press the OK button to exit. 1he screen clears and the script terminates.
13. Close your vindov, and then log out.
*MKuVe 11-20 1he calendar dMaloK box dMsplayMnK Lhe currenL monLh's calendar
You can use Lhe 1ab key
and arrow keys Lo chane
Lhe monLh, day, and year
LhaL is displayed on
your screen
*MKuVe 11-19 1he checklMsL dMaloK box or Lhe dMaloKcheckA scrMpL
62 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
ImTlemeRXMRK MulXMTle DMaloK &oxes WMXLMR a ScVMTX 63
CVeaXMRK a SMmTle ATTlMcaXMoR
You can also use the dialog box to create a simple application to insert and delete records
vithin a tile and to display the tile vith the text box dialog box.1he manager at Pockets
Ped Glare, Inc., nov vants a simple application that allovs a user to enter an employee`s
name, hours vorked, and pay rate. Next you vill create an application comprised ot
three scripts. 1he main script is called dialogmenuB. It allovs the user to insert an
employee`s name, hours, and pay, delete an employee record, using name as input, and
viev the contents ot the pay.dat tile. 1he data to be entered is employee name, hours,
and pay. A script named dialinsA is used to insert the record into the pay.dat tile. A script
named dialdelA is used to delete a record trom the pay.dat tile.
1o crIatI a sMnplI applMcatMon that usIs dMalog boIs
1. Iog in to the Iinux system as a user, and then open a 1erminal
emulation vindov.
2. Create a script named dMalognInuB in your $HOME/bin directory.
3. Insert the tolloving lines ot code to create the dialmenuA script
dialog --menu "Payroll Menu" 10 60 5 1 "Insert Employee"
2 "DeleteEmployee" 3 "View Payroll File"
9 "Exit" 2>$HOME/menu.dat
Num=`cat $HOME/menu.dat`
case $Num in
1} dialinsA ,, # The insert script.
2} dialdelA ,, # The delete script.
3} dialog --textbox $HOME/bin/pay.dat 10 30 ,,
9} dialog --msgbox "Exiting" 10 20 ,,
*} echo "Invalid" ,,
esac
4. Save the script, and then close the editor.
3. Make the script executable.
6. Create a script named dMalMnsA in your $HOME/bin directory.
7. In this script, the user is presented vith three dialog boxes alloving him or
her to enter the name, hours, and pay. 1his data is added as a record to a data
tile named pay.dat. Because each tield needs to be vritten and separated by a
colon, each tield is vritten to a temporary tile. 1hen, command substitution is
used to set three variables, Name, Hours, and Pay to the contents ot those tiles.
linally, each tield is vritten, separated by a colon, to pay.dat.You have seen all
ot these techniques betore. 1o create three input dialog boxes to allov the user
to enter the name, hours, and pay, enter the tolloving
dialog --title "Input Box" --backtitle "Scripting"
--inputbox "Enter Name"9 50 2>>$HOME/name.$$
11
dialog --title "Input Box" --backtitle "Scripting"
--inputbox "EnterHours" 9 50 2>>$HOME/hours.$$
dialog --title "Input Box" --backtitle "Scripting"
--inputbox "Enter Pay" 9 50 2>>$HOME/pay.$$
8. Insert the tolloving lines ot code to set the tields to the contents ot the tiles
Name=`cat $HOME/name.$$`
Hours=`cat $HOME/hours.$$`
Pay=`cat $HOME/pay.$$`
9. Insert the tolloving line ot code to send the tields, separated by a colon, to
the tile named pay.dat
echo ${Name}:${Hours}:${Pay} >> pay.dat
10. Insert the tolloving lines ot code to remove the temporary tiles
rm $HOME/name.$$
rm $HOME/hours.$$
rm $HOME/pay.$$
11. Save the script, close the editor, and then make the script executable.
12. Create a script named dMaldIlA in your $HOME/bin directory.
13. 1he explanation ot deleting a record is explained here but implemented in the
next tev steps.1he user is alloved to enter the name ot the employee to delete.
1he grep command is used to search tor the employee in the tile.1he ~v
option is used to select nonmatching items, vhat you have lett is all the records
but the deleted one.1hese are revritten to a nev tile that is copied back to
pay.dat.1he command grep ~i ~v `$NAME: pay.dat > newpay.dat
accomplishes this. Note `$NAME: is used to select characters at the beginning
ot the tile tolloved by a colon.1his ensures selection based on the name, vhich
is the tirst tield.1he grep ~i option is used to ignore the case. lirst, insert the
tolloving lines ot code to display the input dialog box and redirect the selection
to a temporary tile
dialog --title "Input Box" --backtitle "Scripting"
--inputbox "Enter Name to delete" 9 50 2>>$HOME/name.$$
14. Nov, insert the tolloving line ot code that uses command substitution to set
the variable Name to the contents ot the temporary tile
Name=`cat $HOME/name.$$`
6 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
ImTlemeRXMRK MulXMTle DMaloK &oxes WMXLMR a ScVMTX 65
13. Insert the tolloving line to search tor nonmatching lines. 1hen, redirect those
remaining records (the ones you vant to keep, to another tile, nevpay.dat
grep -i -v $Name: pay.dat > newpay.dat
16. Insert the tolloving lines ot code to copy nevpay.dat to pay.dat and remove
the temporary tile $HOME/name.$$ and nevpay.dat
cp newpay.dat pay.dat
rm $HOME/name.$$
rm newpay.dat
17. Save the script, close the editor, and then make the script executable.
18. Lxecute the script named dMalognInuB. See ligure 11-21. 1he dialog
menu appears.
19. Press 1, and then press LntIr to insert an employee. 1he dialinsA script executes
and displays an input box tor you to enter an employee`s name.
20. Lnter Ralph, and then press the OK button. An input box is displayed alloving
you to enter the hours.
21. Lnter 40, and then press the OK button. An input box is displayed alloving
you to enter the pay.
22. Lnter 3, and then press the OK button. 1he shell prompt is returned.
23. Pun the dMalognInuB script again. 1his time, press 3 to viev the payroll
tile, and then press the OK button. See ligure 11-22. A text box appears
vith the data.
*MKuVe 11-21 1he dMaloKmenu8 scrMpL
11
24. Press the LI1 button to exit the script. 1he shell prompt returns.
23. Pun the dMalognInuB script again. 1his time, press 2 to delete a record, and
then press the OK button. An input dialog box appears alloving you to enter
a name.
26. Lnter Ralph, and then press the OK button. 1he record tor Palph is deleted.
You can rerun the script and viev the tile to make sure.
27. Close your vindov, and then log out.
'HA48)6 7UMMA6Y
1he awk program is a complete programming language alloving you to implement
decision statements, calculations, and looping structures. It also allovs you to
manipulate data vithin tiles and has builtin variables. 1he awk program otters the
use ot several options.
1he awk program lets you use patterns and actions. A pattern is a set ot characters
that can be matched. An action is vhat occurs once a pattern has been matched. At
least a pattern or an action is required. It you leave the pattern ott, the action is
pertormed on the input lines. It you leave the action ott, all input lines matching
the pattern are displayed.
1here are tvo methods you can use in order to get data into your awk script.You
can either pass values to awk or you can prompt users tor data. Lither method
allovs tor a tlexible script because any data can be input into the awk script.
*MKuVe 11-22 VMewMnK Lhe payroll Mle
66 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
6evMew QuesXMoRs 67
You can place awk statements in a script that can be executed by awk.You must
use the ~f option vhen using statements in an awk script. Also, the shell cannot be
used to execute awk scripts because the syntax is ditterent.You can use the awk
builtin variable NR to display the number ot records, this is a torm ot record counting.
You can modity the output ot shell commands vith awk in order to create a
customized command.
1he dialog command is used to create interactive vindovs that are displayed on
the screen. 1he benetit ot using the dialog command to create vindovs-based
screens is that you can build a user-triendly script that meets the needs ot the users,
and at the same time reduce the need tor the users to learn operating system
commands. 1here are certain parameters common to all dialog boxes. 1hey are
text, height, and vidth.
1here are various types ot dialog boxes vith ditterent purposes.You can use dialog
boxes to display messages, create menus tor item selection, or allov user entry.You
can combine dialog boxes into a single script to build a povertul script.
6)VI)W 5U)S8IONS
1. A(n, in awk is vhat is pertormed vhen a data matches a
specitic set ot characters.
a. action
b. pattern
c. decision statement
d. script
2. A(n, in awk is the term used to describe matching a specitic
set ot characters.
a. action
b. pattern
c. decision statement
d. script
3. You can use awk to display the version ot awk.
a. ~V version
b. ~F version
c. ~f version
d. ~W version
11
4. 1he awk pattern that contains statements that are pertormed betore input lines
are read is
a. BEGIN
b. END
c. int
d. print
3. 1he awk option is used to indicate a specitic tield separator.
a. ~V
b. ~F
c. ~f
d. ~W
6. 1he awk builtin variable that equals the total number ot input lines is
.
a. int
b. getline
c. NR
d. BEGIN
7. 1he awk symbol that means contains is .
a. = =
b. ~
c. -
d. <<
8. 1he awk command that allovs you to read data trom the keyboard is
.
a. int
b. getline
c. NR
d. END
9. 1he awk option is used to pass data to awk.
a. ~v
b. ~F
c. ~f
d. ~W
68 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
6evMew QuesXMoRs 69
10. 1he awk pattern that contains statements that are pertormed atter input lines
are read is .
a. BEGIN
b. END
c. int
d. getline
11. 1he dialog box common option that specities the title displayed at the top ot the
screen is .
a. BEGIN
b. backtitle
c. clear
d. shadow
12. Which ot the tolloving dialog boxes allov you to display a message on the screen
a. messbox
b. mbox
c. msgbox
d. message
13. Which ot the tolloving dialog boxes can you use to present the user vith a list
ot choices trom vhich to select
a. msgbox
b. password
c. textbox
d. menu
14. 1he dialog box alloving the user to select only one item trom several items listed
is the dialog box.
a. radiolist
b. infobox
c. textbox
d. checklist
13. Which ot the tolloving dialog boxes allovs the user to select several items trom a list
a. radiolist
b. infobox
c. textbox
d. checklist
11
16. 1he dialog box that allovs you to display the contents ot a tile is .
a. radiolist
b. infobox
c. textbox
d. checklist
17. Which ot the tolloving can properly execute an awk script named script1 using
the suppliers data tile
a. awk ~v scriptl=suppliers
b. awk ~W scriptl suppliers
c. awk ~f scriptl suppliers
d. awk ~f suppliers scriptl
18. Which ot the tolloving statements indicates to use the colon as a delimiter in
awk vhen executing an awk script named avkit on the production data tile
a. awk ~f ~v awkit production
b. awk ~W: ~f awkit production
c. awk ~f: ~F awkit production
d. awk ~F: ~f awkit production
19. Which ot the tolloving statements creates a dialog box vith a height ot 10 and a
vidth ot 20 that displays text indicating the deletion ot a tile
a. dialog ~~messagebox "File created" l0 20
b. dialog ~~msgbox "File deleted" 20 l0
c. dialog ~~textbox "File deleted" l0 20
d. dialog ~~msgbox "File deleted" l0 20
20. Which ot the tolloving statements creates a dialog box, vith a height ot 10, a
vidth ot 30, and displays the contents ot a tile named $HOME/payroll.dat
a. dialog ~~msgbox $HOME/payroll.dat l0 50
b. dialog ~~textbox $HOME/payroll.dat l0 50
c. dialog ~~textbox $home/payroll.dat l0 50
d. dialog ~~fselect $HOME/payroll.dat l0 50 2>payroll.dat
,ANDSON 46OJ)C8S
4VoNecX 11-1
In this project, you vill use the awk command to create a script alloving you to terminate
a process by name.
,ERHWSR
4VSNIGX
70 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
HaRHs-oR 4VoNecXs 71
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named ProNIct11-1 in the HOME/bin directory.
3. Insert the tolloving line ot code using kill, grep, awk, command substitution,
piping, and positional parameters to terminate a process by name
kill -9 ${ps -e [ grep $1 [ awk '{print $1}'}
4. Save the script, and then close the editor.
3. Make the script executable.
6. Open another 1erminal emulation vindov.
7. In the second vindov, run the yes command.
8. In the tirst vindov, type Project11-1 yes.
9. Pecord your results.
4VoNecX 11-2
In this project, you vill create a script that uses the checklist dialog box to allov a user
to enter a menu selection to execute a shell command.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named ProNIct11-2 in the HOME/bin directory.
3. Lse the checklist dialog box to allov the user to enter a 1 to display the current
vorking directory or to enter a 2 to display a listing ot the current user`s directory.
It both 1 and 2 are entered, the vorking directory tolloved by the current
user`s directory should be displayed.
4. Save the script, close the editor, and then make the script executable.
3. Close your vindov, and then log out.
4VoNecX 11-3
In this project, you vill create a script that uses the avkprompt script created in an
earlier exercise and that requires the user to enter both the ID and the name to display
the name and salary.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Copy avkpronpt to $HOME/bin/Project11-3.
3. Make the appropriate code change to require the user to enter both the ID and
the name betore displaying the employee`s name and salary.
4. Pun the script using the employees.dat tile vhich vas created in an earlier exercise.
3. Lnter 1 and SnMth tor the ID and Name, and then record the result.
6. Lnter 1 and LMu tor the ID and Name, and then record the result.
7. Close your vindov, and then log out.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
11
4VoNecX 11-
In this project, you vill create a script that uses the radio list dialog box.1he goal ot this
project is to help you understand hov to implement a radio list dialog box.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named ProNIct11-4 in the $HOME/bin directory.
3. Insert the tolloving lines ot code to create a radio list dialog box.
dialog --radiolist "Radio List" 10 30 5 1 pwd on 2 who off
2>$HOME/menu.dat
CheckStatus=$?
ans=`cat $HOME/menu.dat`
res=`echo $ans [ sed 's/"//g'`
case $res in
"1"} pwd
,,
"2"} who
,,
"1 2"} pwd, who
,,
esac
4. Save the script, and then close the editor.
3. Make the script executable, and then execute the script
6. Perun the script. 1his time select both commands.
7. Close your vindov, and then log out.
4VoNecX 11-5
In this project, you vill create a script that uses the passvord dialog box.1he goal ot this
project is to help you understand hov to implement a passvord dialog box and turther
your knovledge ot dialog boxes.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named ProNIct11- in the $HOME/bin directory.
3. Insert the tolloving lines ot code to create a passvord dialog box.
dialog --passwordbox "Enter value" 9 62 2>$HOME/password.$$
PWStatus=$?
if $PWStatus -ne 0 ]]
then
echo "Exiting..."
exit
fi
ans=`cat $HOME/password.$$`
if $ans = "cactus214" ]] # The password.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
72 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
HaRHs-oR 4VoNecXs 73
then
echo "Correct password"
else
echo "Incorrect password"
fi
rm $HOME/password.$$
4. Save the script, and then close the editor.
3. Make the script executable, execute the script, and then enter fun100 as the passvord.
6. Press the OK button, and then record the results.
7. Pun the script again, and then enter cactus214 as the passvord.
8. Press the OK button, and then record the results.
9. Close your vindov, and then log out.
4VoNecX 11-6
In this project, you vill create a script that uses awk and an if statement to determine
it employees are due a raise.1he script allovs the user to enter a raise threshold amount.
It the employee earns less than the amount entered, he or she vill receive a three percent
raise, othervise, he or she vill earn a tive percent raise. Also, appropriate headers and
tooters are displayed along vith record counters. A message is displayed indicating it the
salaries are over or under the amount entered. linally, the nev amount is vritten to a
nev tile named nevemp.dat.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named ProNIct11- in the $HOME/bin directory.
3. Insert the tolloving lines ot code
BEGIN { print "Id\t Name\t\tSalary New Salary\n" }
{
{if {$4 >= Amt}
{
NS=$4 * 1.03
MSG="Over"
lo++
}
else
{
NS=$4 * 1.05
MSG="Under "
hi++
}
}
printf {"%s:%s:%s:%d\n", $1, $2, $3, int{NS}} > "newemp.dat"
print $1"\t", $2"\t", $3"\t", $4"\t", int{NS}"\t", MSG
,ERHWSR
4VSNIGX
11
print "\n"
}
END { print "Number of employees: " NR "\n\nNumber low: "
lo "\n\nNumber hi: " hi}
4. Save the script, and then close the editor.
3. Make the script executable.
6. Pun the script as tollovs
awk ~v Amt=60000 ~f Project11-6 employees.dat.
7. Viev the output tile, and then record the result.
8. Close your vindov, and then log out.
4VoNecX 11-7
In this project, you vill create a script that uses the input dialog box to delete a tile.1he
goal ot this project is to turther your knovledge ot dialog boxes.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named ProNIct11-7 in the $HOME/bin directory.
3. 1he script needs to allov users to delete a tile it it indeed exists. It the tile exists,
use a yesno dialog box to ask users it they are sure they vant to delete the tile. It
they are indeed sure, then delete it, and display a msg dialog box indicating the tile
has been deleted. It the tile exists and the user decides not to delete it, exit the
script. It the tile does not exist, then display a message box indicating it does not
exist, and then exit the script.
4. Save the script, and then close the editor.
3. Make the script executable.
6. Close your vindov, and then log out.
4VoNecX 11-8
In this project, you vill create a script that copies a tile.You vill use tvo input boxesone
tor users to enter the source tile to copy and one tor users to enter the destination tilename.
1he goal ot this project is to turther your understanding ot dialog boxes.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a script named ProNIct11-8 in the $HOME/bin directory.
3. 1he script needs to allov users to enter the tilename to copy and a destination
tilename. It the tile exists, copy it, and then display a message indicating it has been
copied. It the tile does not exist, indicate that the tile is not present. Lse the
msg box tor displaying all messages to users.
4. Save the script, and then close the editor.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
7 CLaTXeV 11 AHvaRceH 8ecLRMques aRH 8ools
Case 4VoNecXs 75
3. Make the script executable.
6. Close your vindov, and then log out.
'AS) 46OJ)C8S
Case 11-1
1MI vants you to vrite a script application that allovs the user to run operating system
commands by selecting menu items. You may have to create multiple scripts and use
multiple dialog boxes. Hovever, the user must enter the correct passvord, banana3,
betore the operating system command menu appears. It a correct passvord is entered,
allov the user to select trom the tolloving menu items
1. Display the amount ot disk tree space.
2. Lnter an IP address to ping, and then ping the IP address.
3. Display the current number ot users on the system.
4. Delete a tile it present.
3. Copy a tile to another it the source tile is present.
Case 11-2
Basic Manutacturing Corporation has hired you to vrite a small menu-based dialog
script that does the tolloving
1. Allovs a user to add tields into a tile, named parts.dat. 1he tields are Part ID, Part
Name, Price, and Quantity.
2. Deletes a record based upon Part ID.
3. Displays the tile on the screen vithout the colon separators.
4. Allovs the user to press Y, tor Yes, to continually display the menu on the screen.
'EWI
4VSNIGX
'EWI
4VSNIGX
11
77
',%48)6

7'6-48 ()7-+2 %2(


1%2%+)1)28 -779)7
-RXLMWGLETXIV]SY[MPP
(IWMKRERHGVIEXI;IFTEKIWGVMTXW
9RHIVWXERH1]750
'VIEXIWGVMTXWXLEXMRXIVJEGI[MXL1]750
)RLERGIQIRYFEWIHWGVMTXW
9RHIVWXERHXLI6IZMWMSR'SRXVSP7]WXIQ
%HHEWGVMTXEWEPEYRGLEFPIETTPMGEXMSRJVSQXLI+9-HIWOXST
9RHIVWXERHEHHMXMSREPQEREKIQIRXXIGLRMUYIW
'VIEXIGYWXSQQERYEPTEKIW
-
n thMs chapter, you vMll learn hov to manage and desMgn your shells usMng
varMous technMques You vMll learn hov to desMgn and create Web page
scrMpts that Mnclude system commands 1hese Web page scrMpts can be exe-
cuted over a netvork usMng a Web brovser that allovs remote access to shell
commands You vMll learn hov to desMgn scrMpts that Mntertace vMth the
MySQI database management system1hMs vMll allov you to take advantage
ot database technology tor vrMtMng records Mnstead ot havMng to use text tMles
It Ms Mmportant to knov hov to manage your scrMpts Mn an envMronment vhere
a team ot programmers can access the same set ot scrMpts at the same tMme
You vMll learn to manage multMple accesses ot a sMngle scrMpt by dMtterent pro-
grammers through the PevMsMon Control System AddMtMonally, you vMll learn
hov to execute your scrMpt as an applMcatMon that can be launched trom your
desktop Once your shell scrMpts have been vrMtten, you need to create doc-
umentatMon so users can understand hov to utMlMze your scrMpts So, you can
learn hov to create man pages tor the scrMpts you desMgn and create
()SI+NIN+ AND '6)A8IN+ ;)& 4A+) 7C6I48S
Any computer that provides Web page access over the Internet or an intranet is called a
WIb sIrvIr. 1he computer accessing the Web server is called the WIb clMInt. A user
sits at a client computer and uses a Web brovser to connect to the Web server. 1he user
enters either the IP address or DNS name ot the server vithin the brovser. 1he Web
client and Web server use a protocol to request and send Web pages over a netvork.1his
protocol, H]pIrtIt 1ransfIr Protocol (H11P), is part ot 1CPIP. 1he connection
to the server must be available and accessible in order tor the Web server to send the
Web pages to the Web client once they are requested.
A WIb pagI is a tile that is made up ot ASCII text containing special codes that describe
the page layout. 1hese special codes are called H1MI tags and vill be discussed later. A
Web page may have a set ot supporting tiles that contain images and sounds.1he server
reads the Web page tile, sends it to the brovser over the netvork as vell as any sup-
porting tiles tor the page at the request ot the brovser.
You can design a Web page that incorporates the output ot operating system commands
in a script, this is termed a Web page script.1his is advantageous because Web page scripts
allov users access to the Iinux computer via a Web brovser over the Internet or an
intranet, resulting in a more tlexible vork environment
Linux can use any compaLible Web server soLware, buL Red HaL Linux comes
packaed wiLh Lhe Apache Web server soLware. Any Linux compuLer run-
nin Apache is considered a Web server. Apache soLware can be insLalled
durin Lhe insLallaLion o Lhe operaLin sysLem or aLer Lhe insLallaLion usin
Lhe Red HaL Packae Nanaer proram or Lhe rpm command. Reer Lo iLs
man paes or how Lo run Lhis command. AlLhouh you can run oLher Web
servers on Linux, Lhis chapLer assumes Lhe use o Lhe Apache Web server.
When a client computer requests Web pages via the Apache Web server, the server sends
Web pages trom the directory varvvv. Pecall that the directory var is one ot the
system directories discussed in Chapter 2. By detault, Apache uses a subdirectory, named
cgi-bin, tor storing executable scripts.1his is vhere you vill place your Web page scripts
vhen you create them.1he vvv in varvvv, stands tor World Wide Web.You need
root user account access in order to copy scripts to the varvvvcgi-bin directory.
1he Connon GatIva] IntIrfacI (CGI) is a protocol used tor Web servers to be able to
vork vith scripts.As you knov, the Web client uses a Web brovser to access the Web pages.
1he Web pages must be vritten in H]pIrtIt Markup LanguagI, or H1ML, a language
the Web brovser understands. Although tully learning hov to vrite H1MI language
code statements, called tags, is beyond the scope ot this book, you vill learn the H1MI
statements necessary to intertace Iinux scripts vith the Web brovser.1able 12-1 presents
a listing ot a tev ot the H1MI tags vith vhich you need to be tamiliar to create Web
page scripts.
78 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
DesMKRMRK aRH CVeaXMRK Web 4aKe ScVMTXs 79
NosL H1NL Las have a correspondin closin La. 1he use o a orward slash
in ronL o a La name makes Lhe La a closin La. 1here musL be a closin
La or each openin La. AlLhouh Lhe normal codin convenLion is Lo enLer
Las in uppercase, iL is noL a requiremenL.
You can creaLe your Web pae scripLs as a sLandard user. Once Lhey are
compleLe, you need Lo ask your insLrucLor Lo copy Lhese Lo Lhe
/var/www/ci-bin direcLory as Lhe rooL user. l you have rooL access, you can
perorm Lhis operaLion.
Next you vill create a script that includes the basic H1MI code to allov you to create
and viev a Web page vith a Web brovser.You vill then copy the script, or have your
instructor copy it, as the root user, to the varvvvcgi-bin directory. Note that the
use ot the shell`s echo statement is used to intertace a script vith the brovser. When
the script is executed, the output ot the echo statement, as in echo"<HTML>", is used
to literally send the text H1MI~ to the Web brovser tor processing.
1o crIatI a sMnplI WIb pagI scrMpt that dMspla]s thI datI
1. Iog in to the Iinux system as a user, and then open a 1erminal emula-
tion vindov.
2. Create a script named vIbscrMpt1 in your $HOME/bin directory.
H8ML 8aK DescVMTXMoR )xamTle
<B> and </B> 8olds characLers <B>Thistextwillbe
bold.</B>
<CENTER> and CenLers characLers <CENTER>Payroll Employee
</CENTER> List</CENTER>
<HTML> and ldenLiies Lhe beinnin and endin o <HTML>.</HTML>
</HTML> an H1NL documenL
<HEAD> and ldenLiies Lhe beinnin and endin o <HEAD>System
</HEAD> a documenL header Administration Utilities
Screen</HEAD>
<TITLE> and ldenLiies Lhe beinnin and endin <TITLE>System Tools
</TITLE> o a LiLle on Lhe 1iLle bar </TITLE>
<Hn> and ConLrols Lhe size o Lhe header onL; Lhe <H2>Application
</Hn> n represenLs a number rom 1 Lo 6, Utilities</H2>
wiLh 1 bein Lhe laresL onL size and 6
bein Lhe smallesL
<HR> and Used Lo display a horizonLal line <HR></HR>
</HR>
<PRE> and Preserves Lhe preormaLLed ouLpuL, Labs, <PRE></PRE>
</PRE> spaces, and new lines o commands
8able 12-1 A ew H1NL LaKs
12
3. Insert the tolloving required line ot code to indicate vhich shell is to be
used vhen accessing the script.
#!/bin/bash
4. Insert the tolloving line ot code to indicate to the Web server the content
type ot the script. It is called the header line and indicates to the Web brovser
the type ot content the tile contains. Because this script contains text or H1MI
code, you must include this line. It is typically placed at the beginning ot an
H1MI document so the Web server sottvare knovs hov to process the data.
echo "Content-type: text/html"
3. Insert the tolloving line ot code to display a blank line. 1he output ot the
script is not displayed unless there is a blank line atter the header line. 1his is
required tor your Web page script to vork correctly.
echo ""
6. Insert the tolloving line ot code to indicate that this is the start ot the
H1MI section. In Step 8 you vill add the corresponding closing tag, </HTML>
vhich terminates the H1MI code section. Any code betveen the opening
and closing tags is treated as H1MI code.
echo "<HTML>"
7. Insert the tolloving line ot code to display the current date. Note the use ot
command substitution is required here to replace the actual command vith
its date-tormatted output.
echo "Today is " ${date}
8. Insert the tolloving line ot code to indicate that this is the end ot the H1MI
section.
echo "</HTML>"
9. Save the tile, close the editor, and then make the script executable.
1o compleLe Lhe resL o Lhis exercise, you musL be loed in as Lhe rooL user.
l you do noL have access Lo Lhe rooL user password, Lhen have your insLruc-
Lor lo in as Lhe rooL user.
10. Copy the vIbscrMpt1 tile to the /var/vvv/cgM-bMn directory.
11. On the Iinux desktop, double-click the vorld Mcon on the task bar. 1he
Web brovser vindov appears on your screen. It your desktop doesn`t include
the vorld icon, then start your Web brovser ot choice.
All Web-relaLed exercises in Lhis chapLer assume you are usin Lhe Gnome
deskLop wiLh Lhe world icon on Lhe Lask bar.
2SXI
2SXI
80 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
DesMKRMRK aRH CVeaXMRK Web 4aKe ScVMTXs 81
12. In the Address bar, type http//;IFWIVZIV/cgM-bMn/vIbscrMpt1, and then
press LntIr. Insert the IP address or DNS name ot your Web server tor
;e|ser:er. See ligure 12-1.
13. Close your vindovs, and then log out.
You can use this exercise as a model to create other simple Web pages. All you have to
do is to modity Step 7 to include the Iinux command you vant. 1o enhance this sim-
ple Web page script, you can include multiple commands, on separate lines, as vell.
4VeseVvMRK 4VefoVmaXXeH OuXTuX MR a Web 4aKe
Iinux commands use pretormatted output so it is displayed in a user-triendly manner.
Pretormatted output includes characters such as tabs, spaces, and nev lines vhich are
used to make the output more readable. 1he Web server sottvare does not preserve this
pretormatted output by detault. So, it the output ot a command contains pretormats,
these tormats disappear vhen the command executes vithin a Web page script. In the
previous exercise, the tormat ot the output ot the date command vas not preserved by
the Web server sottvare.
In order to preserve the output ot pretormatted tabs, spaces, and nev lines, the H1MI
tag named <PRE> is used. Next you vill display the output ot the who command in a
manner you are accustomed to seeing in the shell.You vill use the <PRE> H1MI tag to
accomplish this. Betore you pertorm this exercise, it may be helptul to see the output ot
a Web page script using the who command vithout the <PRE> H1MI tag. ligure 12-2
shovs the results ot the upcoming exercise vithout the <PRE> and </PRE> H1MI tags
surrounding the who command. Notice hov the output ot who is not tormatted as you
are accustomed to seeing it.
*MKuVe 12-1 AccessMnK Lhe webscrMpL1 Web paKe scrMpL whMch dMsplays Lhe daLe
lP address o Web server
12
1o crIatI a sMnplI WIb pagI scrMpt that usIs thI <PRE> tag to prIsIrvI thI prI-
fornattId output of LMnu connands
1. Iog in to the Iinux system as a user, and then open a 1erminal emula-
tion vindov.
2. Create a script named vIbscrMpt2 in your $HOME/bin directory.
3. Insert the tolloving lines ot code to reterence the shell, indicate the content
type, and display a blank line atter the header
#!/bin/bash
echo "Content-type: text/html"
echo ""
4. Insert the tolloving line ot code to indicate H1MI code is to come
echo "<HTML>"
3. Insert the tolloving line ot code to preserve the output ot Iinux commands
echo "<PRE>"
6. Insert the tolloving lines ot code to display a message line and execute the
who command
echo "The users logged on are: "
who
7. Insert the tolloving line ot code to close the preservation ot pretormatted output
echo "</PRE>"
8. Insert the tolloving line ot code to terminate the H1MI code
echo "</HTML>"
*MKuVe 12-2 A Web paKe scrMpL LhaL does noL preserve Lhe ouLpuL o a command
82 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
DesMKRMRK aRH CVeaXMRK Web 4aKe ScVMTXs 83
9. Save the tile, and then close the editor.
10. Make the script executable.
11. Properly gain root user access either on your ovn or through your instructor.
12. Copy the vIbscrMpt2 tile to the /var/vvv/cgM-bMn directory.
13. Open your Web brovser.
14. In the Address bar, type http//;IFWIVZIV/cgM-bMn/vIbscrMpt2, and then
press LntIr. Again supply the correct IP address or DNS name ot your Web
server. ligure 12-3 shovs the results ot this exercise.Your output may ditter.
Because you used the H1MI tags, the output appears the same as it you
entered the who command at the shell prompt. Compare ligure 12-2 and
ligure 12-3 and notice hov the output ditters vhen the <PRE> tag is used.
13. Close your vindovs, and then log out.
CusXomMzMRK Web 4aKe ScVMTXs wMXL AHHMXMoRal H8ML 8aKs
You can include additional H1MI tags trom 1able 12-1 in order to customize your Web
page.You add these H1MI tags to make the Web page script more visually appealing or
to have specitic text stand out on your Web page. lor example, to center text, you use
the tolloving statement
echo "<CENTER>"
echo "The users logged on are:"
echo "</CENTER>"
*MKuVe 12-3 AccessMnK Lhe webscrMpL2 Web paKe scrMpL LhaL uses a preormaLLed
ouLpuL LaK
12
1he text that you vant to center tollovs the initial H1MI statement, and then you ter-
minate the centering tag vith the matching H1MI closing tag.You can have multiple
H1MI tags in sequence. lor example, in the code that tollovs, the text 1he users
logged on are is centered, bolded, and displayed vith heading level 1.
echo "<CENTER>"
echo "<B>"
echo "<Hl>"
echo "The users logged on are: "
echo "</Hl>"
echo "</B>"
echo "</CENTER>"
You can also place Lhe openin and closin H1NL Las on a sinle line as in
Lhis example o Lhe openin Las shown Lo cenLer, use headin level 1, and
bold, echo "<CENTER><B> <H1> "
Next you vill create a Web page script that includes additional H1MI tags to shov you
hov to add these tags to customize your Web page. Pertorming this exercise vill help
you understand hov to use these additional tags in a Web page script.
1o crIatI a WIb pagI scrMpt that usIs addMtMonal H1ML tags
1. Iog in to the Iinux system as a user, and then open a 1erminal emula-
tion vindov.
2. Create a script named vIbscrMpt3 in your $HOME/bin directory.
3. Insert the tolloving lines ot code to reterence the shell, indicate the content
type, place a blank line atter the header, use the pretormatted output tag, and
indicate that H1MI code vill tollov
#!/bin/bash
echo "Content-type: text/html"
echo ""
echo "<HTML>"
echo "<PRE>"
4. Insert the tolloving lines ot code to center, bold, and use heading level 1 tor
text that is displayed on the screen. Notice each opening tag has a correspond-
ing closing tag.
echo "<CENTER>"
echo "<B>"
echo "<H1>"
echo "The users logged on are: "
echo "</H1>"
echo "</B>"
echo "</CENTER>"
8 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
DesMKRMRK aRH CVeaXMRK Web 4aKe ScVMTXs 85
3. Insert the tolloving lines ot code to use heading level 2 and display the out-
put ot the who command on the screen
echo "<H2>"
who
echo "</H2>"
6. Insert the tolloving lines ot code to close the pretormatted output tag and
close the H1MI text tag
echo "</PRE>"
echo "</HTML>"
7. Save the tile, and then close the editor.
8. Make the script executable.
9. Properly gain root user access either on your ovn or through your instructor.
10. Copy the vIbscrMpt3 tile to the /var/vvv/cgM-bMn directory.
11. Open your Web brovser.
12. In the Address bar, type http//;IFWIVZIV/cgM-bMn/vIbscrMpt3, and then
press LntIr. Again supply the correct IP address or DNS name ot your Web
server. ligure 12-4 shovs the results ot this exercise.
13. Close your vindovs, and then log out.
JusL remember when you have openin and closin Las LhaL everyLhin
beLween Lhe La pairs is subjecL Lo whaL Lhose Las do. Also, make sure LhaL
each openin La has a correspondin closin La.
*MKuVe 12- AccessMnK Lhe webscrMpL3 Web paKe scrMpL LhaL uses addMLMonal H1NL LaKs
Lo cusLomMze scrMpLs
12
AHHMRK Web SeVveV VaVMables Xo a Web 4aKe ScVMTX
You can turther enhance your Web page script by incorporating Web server variables.
1ypically you do this to customize your Web page vith additional intormation about
the Web server such as the Web server name, the server protocol and version, and the
Web server sottvare the server is running. 1able 12-2 provides a listing ot a tev ot the
Web server variables that can be used in a Web page script.
A practical use ot adding Web server variables is to display intormation about the Web
server in a Web page script that deals vith server utilities. ligure 12-3 shovs a Web page
script that includes many ot the variables shovn in 1able 12-2. ligure 12-6 displays the
script shovn in ligure 12-3. Notice that in ligure 12-6 you can see the server`s address,
name, sottvare and version, and protocol and version.
Also, in the script in ligure 12-3, see the who command using the pipe symbol to pass
its output to the awk command to display only tvo tields. 1his demonstrates hov you
can put more complex commands vithin your Web page script.
VaVMable DescVMTXMoR )xamTle
DOCUMENT_ROOT DirecLory where Web paes are echo"The directory
sLored and loaded containingWebpagesis
$DOCUMENT_ROOT"
SCRIPT_FILENAME PaLh name o Lhe scripL LhaL is echo"The scriptnameis
execuLin $SCRIPT_FILENAME"
SERvER_ADMIN L-mail address o Lhe Web server echo "ContacttheWeb
adminisLraLor master:$SERvER_ADMIN"
SERvER_NAME Server's lP address or DNS name echo"Theserveraddress
is$SERvER_NAME"
SERvER_PROTOCOL ProLocol and version used by Lhe echo"The protocolis
Web server $SERvER_PROTOCOL"
SERvER_SOFTWARE Web server soLware Lhe Web echo"TheWebsoftware
server is runnin runningonthisWebserver
is:$SERvER_SOFTWARE"
8able 12-2 A ew web server varMables
86 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
DesMKRMRK aRH CVeaXMRK Web 4aKe ScVMTXs 87
*MKuVe 12-6 ResulLs o a Web paKe scrMpL whMch uses addMLMonal H1NL LaKs Lo
cusLomMze scrMpLs
#!/bin/bash
echo "Content~type: text/html
echo ""
echo "<PRE>"
echo "<HTML>"
echo "<HEAD>"
echo "<H2>"
echo "<HR>"
echo "<CENTER>"
echo "<System Utilities"
echo "</CENTER>"
echo "</HEAD>"
echo "</H2>"
echo "<Server Name: $SERvER_NAME"
echo "Script Name: $SCRIPT_NAME"
echo "Server Software: $SERvER_SOFTWARE"
echo "Server Protocol": $SERvER_PROTOCOL"
echo "<TITLE>"
echo "System Admin Web Page"
echo "</TITLE>"
echo "<B>"
echo "The file system usage: "
echo "</B>"
df
echo "<B>"
echo "The users logged on:"
echo "</B>
who]awk '{print $1 " at " $5}'
echo "</PRE>"
echo "<HR>"
echo "</HTML>"
*MKuVe 12-5 A Web paKe scrMpL LhaL uses Web server varMables Lo enhance a sysLem
uLMlMLMes scrMpL
12
UsMRK OXLeV CommaRHs MR Web 4aKe ScVMTXs
You can place other commands, such as decisions, in your Web script. 1his allovs you to
customize your Web pages tor certain conditions you may vant to test. lor example, say
you vant to implement a decision structure to display a message based upon hov many
users are logged in to the Iinux computer system. In the code shovn in ligure 12-7, you
can see a moditication to ligure 12-3 vhich uses an if statement to determine hov
many users are logged in.
Notice in ligure 12-7 that the number ot users on the system is held in a variable named
num. Next the variable num is tested using the shell`s if statement. It its contents are
greater than zero, then a message is displayed along vith the output ot the who com-
mand. It num is less than or equal to zero, then a message indicating that no users are
logged in is displayed. Notice the use ot the H1MI tag <B> surrounding only the mes-
sages tor each ot the tvo conditions in the decision structure.
You could subsLiLuLe Lhe irsL sLaLemenL in Lhe parLial scripL shown in
Fiure 12-7, wiLh Lhe wc ~l sLaLemenL which counLs Lhe lines piped Lo iL by
Lhe who command. (NoLe LhaL Lhe opLion is "l" as in "line" on Lhe wc
command.)
num=${who]awk 'END {print NR}'|
if $num ~gt 0
then
echo "<B>"
echo "These are the users logged on:"
echo "</B>"
who
else
echo "<B>"
echo "No users logged on now."
echo "</B>"
fi
*MKuVe 12-7 A parLMal Web paKe scrMpL whMch uses addMLMonal shell loKMc Lo cusLomMze scrMpLs
88 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
URHeVsXaRHMRK MySQL 89
9ND)6S8ANDIN+ 1Y750
M]SQL (M] StructurId QuIr] LanguagI) is a relational database management sys-
tem that allovs you to store data in database tables vithin database tiles. You can also
query the data vith MySQI statements. 1he term relational means there is a rela-
tionship betveen the tields stored in a table.You can incorporate MySQI code to access
a database vithin a shell script.You use MySQI because it provides much greater con-
trol, etticiency, and management ot data than processing data in a text tile as you`ve done
in Chapter 9. MySQI allovs other programming languages such as C, C, ava, and
COBOI to interact vith it. Iike learning H1MI, completely learning MySQI is
beyond the scope ot this book. Hovever, you vill learn the necessary MySQI code
statements to pertorm basic tasks such as selecting, inserting, updating, and deleting data
vithin a database. 1he main tocus, hovever, vill be on hov you can integrate the tech-
nology ot MySQI vithin shell scripts.
Red HaL Linux comes wiLh daLabase manaemenL soLware named NySQL.
However, you may need Lo insLall iL, and i you do, you musL be loed in as
Lhe rooL user. l iL is already insLalled and runnin, Lhere is a mysqld daemon
runnin in Lhe process Lree. You can use eiLher Lhe ps ~elf]grep
mysqld command Lo check Lo see i Lhe daemon is runnin, or you can exe-
cuLe Lhe servicemysqldstatus command as Lhe rooL user. l you don'L
have access Lo Lhe rooL user accounL, ask your insLrucLor or assisLance.
lirst, you need to understand database terminology in order to be able to vrite MySQI
code in a shell script.A databasI nanagInInt s]stIn (DBMS) is sottvare that allovs
you to manage and access data. MySQI is an example ot a DBMS. When you reterence
a tield vithin a database it is called a colunn, and a record is called a rov. A tablI is a
collection ot related columns and rovs. A databasI fMlI consists ot one or more tables
that contain the data. You vrite data to the table that is contained vithin the database
tile. A quIr] is the term used to describe a DBMS statement that retrieves or manipu-
lates data vithin a table.
1he basic tasks that you vill integrate vithin shell scripts are listed in 1able 12-3.
AcXMoR SXaXemeRX DescVMTXMoR )xamTle
insert Allows inserLion o daLa insert into paydb.paytable{name,
inLo a daLabase Lable rate, hours| values {'Jan
Banel','43','38'|
select Allows selecLion o daLa select name, rate, hours from
rom a daLabase Lable paydb.paytable
delete Allows deleLion o daLa delete from paydb.paytable where
rom a daLabase Lable name='Mike Brownlee'
update Allows updaLe o daLa update paydb.paytable set
inLo a daLabase Lable hours='40'
8able 12-3 A ew NySQL sLaLemenLs
2SXI
12
SelecXMRK DaXa
One ot the most usetul MySQI statements is the select statement. You use this to
viev a portion or all ot the data vithin a database table. It takes the tolloving basic torm
select co1umns from dataoase.tao1e where co1umn='data'
1his is vhere co1umns is one or more columns separated by a comma. 1he term
dataoase is the name ot the database and tao1e is the table vithin the database tile.
larmers, Inc. is a company that sells tarm equipment.1hey use MySQI on a Iinux com-
puter and have a database tile named tarms. 1he tarms database only has one table in it
right nov. 1he table is named products. 1he products table contains these columns ID,
Name, Price, and Quantity. In this case, ID is the primary key. Pecall the concept ot a
primary key is discussed in Chapter 1. Iook at an example ot hov the select action
statement might vork.
1o display the ID and Price columns vithin the products table ot the tarms database,
you enter selectID,Pricefromfarms.products.You can also use a where
clause vith MySQI statements as a decision statement. 1his is usetul tor selecting
columns matching a specitic condition. lor example, to select the Name column and
Price column ot the product matching an ID ot 101, you enter select Name,
Pricefromfarms.productswhereID = "l0l".You can select all the columns
vithin the tarms.products database by using the asterisk symbol, as in this example
select*fromfarms.products.
IRseVXMRK DaXa
You use insert tor inserting or adding nev data to a table. It takes the tolloving
basic torm
insert into dataoase.tao1e{co1umns| values{'data'|
1his is vhere co1umns are equal to the values specitied by data. It larmers, Inc. vants
to add a nev product to the products table such as a nev tractor, vith an ID ot 102 and
a Price ot s30,000, they enter
insert into farms.products{ID, Name, Price|
values {'l02', 'Big Tractor l000XL', '50000'|
Data is assigned, by position, to the columns using the values reserved vord. So,
. farms.products{ID, Name, Price| values {'l02', 'Big Tractor
l000XL', '50000'|, is similar to saying ID='l02', Name='Big Tractor l000XL',
and Price='50000' in the products table ot the tarms database.
DeleXMRK DaXa
1he delete statement is used tor deleting data vithin a table. It takes the tolloving
basic torm
delete from dataoase.tao1e where co1umn='data'
90 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
URHeVsXaRHMRK MySQL 91
In this case, the rov is deleted vhere the co1umn is equal to the value specitied by
data. It larmers, Inc. decides they no longer need the tractor vith an ID ot 100, they
enter a statement such as delete from farms.products where ID= 'l00'.
UTHaXMRK DaXa
When you vant to modity current data vithout having to completely delete the old rov
and insert a nev one, you use the update statement. It takes the tolloving basic torm
update HEXEFEWIXEFPI set GSPYQR='HEXE' where GSPYQR='HEXE'
In this case, you set co1umn1 to equal data1 vhere co1umn2 matches data2. lor
example, the nevest tractor tor larmers, Inc. has sold so vell that the company has
decided to raise the price. 1hey vant to increase the price by 300 dollars to s30,300.
1he update statement appears as tollovs
update farms.products set Price='50500' where ID='l02'
SeXXMRK Access Xo MySQL
Iike most SQI-based products, MySQI allovs you to control access to vhat a user can
do vithin the database. Betore a user can use the statements shovn in 1able 12-3 vithin
MySQI or a shell script, the user must be authorized to do so. lailure to authorize a
user to use the MySQI statement results in an error.
Betore you get started vith MySQI, you need to set the root user`s passvord vithin
MySQI.1his root user is the Database Administrator (DBA,. A DBA is a person respon-
sible tor managing a DBMS. 1his passvord is ditterent trom the Iinux root user`s pass-
vord. Hovever, you must be logged in as the Iinux root user to set the MySQI user
passvord. Here the statement only needs to be run once at the Iinux command line as
the Iinux root user. It you don`t have access to the Iinux root user account, ask your
instructor tor assistance. 1he code to set the DBA (root, user`s passvord to cactus100
tollovs. Note the ~u option, vhich stands tor user, precedes the DBA root username.
1he ~password option precedes the actual passvord you vant to assign.
mysqladmin ~u root password cactusl00
MySQI contains a detault system database tile called mysql, vhich contains several tables
to store database system-related data. It stores data including the type ot access a user has
to a table and vhat host names the users can use. MySQI comes installed assuming only
the DBA has unrestricted access to all database tiles trom any computer.1hus, to manip-
ulate these tables you must be acting as the DBA root user. 1he tables you need to use
to allov users access to your database, are db and users. Note that this is not done
strictly tor alloving scripts to interact vith your database, it is done to allov users access
to your database regardless ot the programming language used to access the DBMS.You
need to insert data into these tables tor the user to access the database tile you create.
Additionally, you need to set MySQI access tor users trom the localhost. 1he term
localhost is a DNS name that denotes the computer to vhich a user is logged in.
12
1o set a user`s access to MySQI trom the Iinux computer he or she is logged in to, or
the localhost, you need to insert a rov vithin the mysql system database.1he tolloving
MySQI statement shovs you hov to insert a user named molly to the user table tor
access to MySQI trom the localhost.
mysql ~uroot ~pcactusl00 ~e "insert into user {host,
user|values {'localhost', 'molly'|" mysql
Note that there is no space betveen the ~p option and the actual passvord ot cactus100.
It is important to understand that you must set the privileges tor each user so he or she
can select, insert, update, and delete data trom the database. Once the tolloving state-
ment is executed, Molly has the ability to select, insert, update, and delete data vithin
the tarms database trom the localhost.
mysql ~uroot ~pcactusl00 ~e "insert into db {host, db,
user, select_priv, insert_priv, update_priv, delete_priv|
values{'localhost', 'farms', 'molly', 'Y', 'Y', 'Y',
'Y' |" mysql
1he column host is set to localhost. 1he column db is set to tarms and the column
user is set to Molly. Note the last tour columns are used to assign privilege to use one
ot the statements listed in 1able 12-3. You can see that columns select_priv,
insert_priv, update_priv, and delete_priv are set to Y, giving the user the
privilege to select, insert, update, and delete.
When makin chanes Lo Lhe mysql daLabase you may need Lo reload Lhe
NySQL Lables so Lhe chanes Lake place. 1o do Lhis iven Lhe previous exam-
ple, you enLer mysqladmin ~uroot~pcactus100reload.
Some ot the MySQI options that are used in previous statements are listed in 1able 12-4.
Become tamiliar vith these statements because you vill use them in shell scripts.
AcXMoR SXaXemeRX DescVMTXMoR )xamTle
OTXMoR
~e Allows you Lo ive NySQL mysql~e"insertinto
execuLable code Lo run mytable{name,number|
values{'Vien','lll'|"mydb
~u Allows you Lo lo in Lo NySQL mysql~ubob
wiLh a username
~p Allows you Lo ive a password mysql ~u bob ~p bobspassword
Lo NySQL
8able 12- A ew NySQL opLMons
92 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
URHeVsXaRHMRK MySQL 93
CVeaXMRK MySQL DaXabases aRH 8ables
Betore you can manipulate data in MySQI, you must create the database and at least
one table to store the data.1his is a requirement ot most database management sottvare,
including MySQI. 1he command to create a database is as tollovs
create database dataoase
1his is vhere dataoase is the name ot the database you vant to create. 1o create the
tarms database tor larmers, Inc. and log in to the MySQI sottvare as the root user vith
a passvord ot cactus100, you enter mysql ~uroot ~pcactusl00 ~e"create
database farms".
Another requirement ot most database management sottvare is the need to create a table
vithin the database tile. 1he general tormat is as tollovs
create table tao1e{co1umn co1umn~def1n1t1on.|, dataoase
1his is vhere tao1e is the name ot the table to create vithin the dataoase. Note that
you are creating the column names and detinitions too.
In the tolloving code, the products table is created vithin the tarms database. Note the
variable ID is detined as an integer ot tvo integer positions. Name is detined as 20 char-
acters, and both Price and Quantity are detined as integers ot tvo positions.
mysql ~uroot ~pcactusl00 ~e"create table products {
ID int{2|,
Name char{20|,
Price int{2|,
Quantity int{2|
|," farms
You musL creaLe Lhe daLabase ile beore you creaLe any Lables wiLhin iL.
Next you vill set the user`s access to MySQI and create the MySQI database and tables.
You vill allov your Iinux user name access to insert, delete, update, and select data tor the
tarms database.You vill also create the tarms database and the products table vithin tarms.
1he steps in this exercise need to be pertormed only once to set up access and must be done
prior to the inserting, deleting, selecting, and updating ot the data vithin the database table.
1o sIt usIr accIss and to crIatI a databasI and a tablI
1. Iog in to the Iinux system as a user, and then open a 1erminal emula-
tion vindov.
2. 1o add your user account so you can access MySQI trom your Iinux
computer, enter the tolloving line ot code. Be sure to use ourusername tor
your Iinux user account name.
12
mysgl -uroot -pcactus100 ~e "insert into user {host,
user} values {'localhost', 'your-username'}" mysgl
3. 1o give your Iinux user account the ability to select, insert, update, and
delete data vithin the tarms database, enter the tolloving line ot code. Again,
replace ourusername vith your Iinux user account name.
mysgl -uroot -pcactus100 ~e "insert into db {host, db,
user, select_priv, insert_priv, update_priv,
delete_priv} values{'localhost', 'farms', 'your-
username', 'Y', 'Y', 'Y', 'Y' }" mysgl
4. 1o create the MySQI database named tarms, enter the tolloving line ot code
mysgl -uroot -pcactus100 ~e"create database farms"
3. 1o create the products table vithin the tarms database enter the tolloving
lines ot code
mysgl -uroot -pcactus100 -e"create table products {
ID int{2},
Name char{20},
Price int{2},
Quantity int{2}
}," farms
6. 1o reload MySQI, enter the tolloving line ot code
mysgladmin -uroot -pcactus100 reload
7. Close your vindov, and then log out.
'6)A8IN+ 7C6I48S 8HA8 -N8)6*AC) WI8H 1Y750
Nov that you`ve had the chance to learn about the basics ot MySQI, you vill learn
hov to create scripts that use MySQI code statements. In this section, you vill create a
shell script tor each ot the tour MySQI statements that allovs you to insert, select,
delete, and update data vithin the tarms database and products table.
CVeaXMRK a ScVMTX Xo IRseVX DaXa
Next you vill create a shell script to insert data into the products table vithin the tarms
database.You use the read command to accept the data trom the keyboard. 1he data is
then inserted into the table
1o crIatI a scrMpt that allovs ]ou to MnsIrt a rov Mn a databasI
1. Iog in to the Iinux system as a user, and then open a 1erminal emula-
tion vindov.
2. Create a script named sqlfarnsMns in your $HOME/bin directory.
3. Insert the tolloving lines ot code to accept data trom the keyboard. Notice
the number ot variables matches the number ot columns in the database tile.
read -p "Enter ID: " ID
9 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
CVeaXMRK ScVMTXs XLaX IRXeVface wMXL MySQL 95
read -p "Enter name: " Name
read -p "Enter price: " Price
read -p "Enter guantity: " Quantity
4. Insert the tolloving line ot code to execute the MySQI insert statement.
1he columns in the tarms.products database table are set vith the values
clause. 1he variables that vere entered in the previous step are used because
they vill be read in vhen the script executes. Note a dollar sign precedes
each variable name in order to reter to the contents ot the variable.
mysgl -e"insert into farms.products {ID, Name, Price,
Quantity} values {'$ID', '$Name', '$Price',
'$Quantity'}"
3. Save the tile, and then close the editor.
6. Make the script executable.
7. Pun the script using the tolloving data. lor the ID, enter 1. lor the name,
enter BMg RMg 1ractor. lor the price, enter 12000, and tor the quantity,
enter 4. 1he tields are inserted in the database, and the prompt returns. See
ligure 12-8.
8. Perun the script vith this data. lor the ID, enter 2. lor the name, enter LMttlI
RMg 1raMlIr. lor the price, enter 700, and tor the quantity, enter 8. 1he tields
are inserted in the database, and the prompt returns. See ligure 12-8.
9. Perun the script vith the tolloving data. lor the ID, enter 3. lor the name,
enter BMg 1op SMlo. lor the price, enter 2000, and tor the quantity, enter 2.
1he tields are inserted in the database, and the prompt returns. See ligure 12-8.
10. Close your vindov, and then log out.
*MKuVe 12-8 VarMous resulLs o Lhe sqlarmsMns
12
CVeaXMRK a ScVMTX Xo SelecX DaXa
Next you vill create a shell script to select data trom the products table vithin the tarms
database.1he script allovs the user to enter an ID trom the keyboard.1hen, the MySQI
select statement selects the rovs in the database matching the ID that is entered. It
there is a match, the rov is displayed.You make the script tlexible by alloving the user
to simply press Lnter to select all ot the rovs vithin the tarms database. 1his is done
vith the shell`s if statement.
1o crIatI a scrMpt that allovs ]ou to sIlIct a rov Mn a databasI
1. Iog in to the Iinux system as a user, and then open a 1erminal emula-
tion vindov.
2. Create a script named sqlfarnssIl in your $HOME/bin directory.
3. Insert the tolloving lines ot code to accept the ID trom the keyboard and
create the decision statement that allovs the user to enter either an ID or
press Lnter to select all rovs in the database. Note that it the ID is empty,
then all ot the rovs are displayed.
read -p "Enter ID to select: " ID
if $ID = "" ]]
then
mysgl -e"select * from farms.products"
else
mysgl -e"select * from farms.products where ID = '$ID'"
fi
4. Save the tile, and then close the editor.
3. Make the script executable.
6. Pun the script, and then press LntIr at the prompt. See ligure 12-9. All ot
the rovs are displayed.
7. Pun the script again, enter 2 tor the ID, and then press LntIr. See ligure 12-9.
1he data tor Iittle Pig 1railer is displayed.
8. Pun the script one last time, enter 3 tor the ID, and then press LntIr. See
ligure 12-9. 1he data tor Big 1op Silo is displayed.
9. Close your vindov, and then log out.
96 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
CVeaXMRK ScVMTXs XLaX IRXeVface wMXL MySQL 97
CVeaXMRK a ScVMTX Xo DeleXe DaXa
Next you vill create a shell script to delete data trom the products table vithin the tarms
database. 1he script allovs the user to enter an ID trom the keyboard.
1o crIatI a scrMpt that allovs ]ou to dIlItI colunns Mn a databasI
1. Iog in to the Iinux system as a user, and then open a 1erminal emula-
tion vindov.
2. Create a script named sqlfarnsdIl in your $HOME/bin directory.
3. Insert the tolloving lines ot code to accept the ID trom the keyboard and to
create the statement to delete the rov in the database matching the ID.
read -p "Enter ID to delete: " ID
mysgl -e"delete from farms.products where ID='$ID'"
4. Save the tile, and then close the editor.
3. Make the script executable.
6. Pun the script, enter 2 tor the ID, and then press LntIr. 1he data tor Iittle
Pig 1railer is deleted.
7. Pun the sqlfarnssIl script to verity that the rov vith an ID ot 2 has been
deleted, and then press LntIr to display all ot the rovs. See ligure 12-10. All
rovs except the one vith an ID ot 2 are displayed.
8. Close your vindov, and then log out.
*MKuVe 12-9 1he ouLpuL o mulLMple execuLMons o Lhe sqlarmssel scrMpL
SLep 6: all o Lhe rows are
displayed
Only indicaLed rows are
displayed
12
CVeaXMRK a ScVMTX Xo UTHaXe ColumRs MR a 6ow
Next you vill create a shell script to update a column in a rov vithin the products table
in the tarms database. 1he script allovs the user to enter an ID trom the keyboard. It a
matching ID is tound in the database, then the price is updated.
1o crIatI a scrMpt that allovs ]ou to updatI a colunn Mn a databasI
1. Iog in to the Iinux system as a user, and then open a 1erminal emula-
tion vindov.
2. Create a script named sqlfarnsupdatI in your $HOME/bin directory.
3. Insert the tolloving lines ot code to accept the ID and price trom the key-
board and create the statement to update the Price column in the database
matching the ID.
read -p "Enter ID: " ID
read -p "Enter new price: " Price
mysgl -e "update farms.products set Price='$Price' where
ID='$ID'"
4. Save the tile, and then close the editor.
3. Make the script executable.
6. Pun the script, and then enter 1 tor the ID and 13000 tor price. 1he price
is updated.
*MKuVe 12-10 1he ouLpuL o Lhe sqlarmsdel scrMpL execuLMon
98 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
)RLaRcMRK MeRu-baseH ScVMTXs 99
7. Pun the sqlfarnssIl script to verity the price update, and then press LntIr
to display all ot the rovs. See ligure 12-11. All the rovs are displayed. 1he
price is updated tor the ID ot 1.
8. Close your vindov, and then log out.
You can pertorm calculations on columns in a table. lor example, it you vanted to cal-
culate the price multiplied by the quantity in the tarms database and create a nev head-
ing named 1otal to display the result, you enter the tolloving mysql ~e "select
ID, Name, Price, Quantity, Price*Quantity Total from farms.prod
ucts where ID='$ID'".
)NHANCIN+ 1)NU&AS)D 7C6I48S
1here are several commands that can be used to create a custom design tor your menu-
based scripts to make the script more user-triendly. Keep in mind that the term user-
triendly is relativevhat one user may like, another may dislike, so you should caretully
moderate your customized changes.
Some ot the types ot custom changes you can make to enhance your scripts include cus-
tomizing one ot the shell`s prompts in a script that displays menus to employ a user-
triendly prompt tor users indicating vhat they are supposed to enter, another example
is bolding and underlining text or changing the color ot the letters that appear on the
screen and thus alloving a user to highlight important intormation on the screen.You
can also cause a beep to sound in the event the user selects an invalid menu item. 1his
alerts users that they`ve pressed an invalid key.
*MKuVe 12-11 1he resulL o Lhe execuLMon o Lhe sqlarmsupdaLe scrMpL
12
1he tvo commands that assist in enhancing menu-based scripts are
1he select command
1he tput command
CVeaXMRK MeRus wMXL XLe WIPIGX CommaRH
1he select command can be used to customize a menu. 1his command is similar to
creating menus using the case statement vith loops in a script. Hovever the select
command ditters because the concept ot looping is included vithin its structure. 1he
select command vas specitically developed to make it easier to code a menu in a
script. It takes the tolloving general torm
select name in word1 word2.
do
11st
done
1he select command lists each word on the screen in a column tormat. A number,
starting vith one and corresponding to the vord`s position in the list, precedes each
item, this is done automatically by the select command.1he user can enter a number
in the list.When the number is selected, then the value ot name equals the vord selected.
1his is like coding casenamein vhen using the case command. Once the num-
ber is entered, the command tor the number in 11st executes.
1he Iinux prompt, PS3, is used by the select command to set the text to prompt the
user. It the user simply presses Lnter at the prompt, then the list ot vords, along vith
the prompt, are displayed once more. 1he shell automatically places the line that is
selected in the shell variable named REPLY.
1hink o Lhe select command as a combinaLion o Lhe case sLaLemenL and
a loopin sLrucLure such as while.
Iook at an example that uses the select command. A list ot commands is displayed
preceded by a number. 1he user presses the number, and the corresponding command
executes. In the tolloving code tor a script named selA, the shell`s select prompt, PS3,
is set. 1he select command displays items tor the user to select. It the user presses 1,
then the variable named cmd contains the who command. Next, the do $cmd done
statement causes the who command to execute. It the user presses 2, then the variable
named cmd contains the pwd command, and the pwd command executes. Iikevise, it
the user presses 3, the date command executes.
PS3="Enter Command: "
select cmd in who pwd date
do
$cmd
done
500 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
)RLaRcMRK MeRu-baseH ScVMTXs 501
ligure 12-12 shovs the contents ot selA and the output ot executing it tour times. lor
the tirst three times selA is executed, the numbers 1, 2, and 3 are entered, and the asso-
ciated command is executed. In the tourth and last execution ot selA, the Lnter key is
pressed. Notice that the items are displayed again.
A shortcoming ot the select command is that both the name in the vord list and the
command that is executed vhen its corresponding number is selected must be named
the same. Based on the previous example, it you vant to use the select command to
insert a rov in the MySQI tarms database using the script sqltarmsins, you vould need
to use sqltarmsins tor both the name in the vord list and the name ot the script that
is executed it a user chooses to insert a rov in the tarms database. 1o some people this
may not be very user-triendly. So, to create a user-triendly name in the vord list that is
ditterent trom the actual script being executed, you can use the case statement.
Next you vill create a main menu using the MySQI tarms script and database you
created in the previous section and incorporate the select and case statements.
1o crIatI a scrMpt usMng thI select and case statInInts
1. Iog in to the Iinux system as a user, and then open a 1erminal emula-
tion vindov.
2. Create a script named sqlfarnsnInu in your $HOME/bin directory.
3. Insert the tolloving line ot code to set the prompt tor the select statement
PS3="Enter choice: "
*MKuVe 12-12 1he conLenLs o Lhe selA scrMpL and Lhe ouLpuL o several execuLMons
12
4. Insert the tolloving lines ot code to create the select vord list
select ans in Insert Delete Select Update Quit
do
3. Insert the tolloving lines ot code tor the case statement. Notice the names in
the vord list are ditterent than the actual script being executed. It you compare
this to the script named selA, you can see the ditterence. 1he select state-
ment displays 1, Insert tor the tirst menu item, 2, Delete tor the second
menu item, and so on until it tinally displays 3, Quit.When the user presses 1,
the sqltarmsins script executes. When the user presses 2, the sqltarmsdel script
executes. 1his same pattern occurs tor the items 3 and 4 as vell. It the user
presses 3, then the code to break out ot the select statement executes.
case $ans in
Insert} sglfarmsins ,,
Delete} sglfarmsdel ,,
Select} sglfarmssel ,,
Update} sglfarmsupdate ,,
Quit} echo "Quitting"
break ,,
*} echo "Invalid Choice!" ,,
esac
6. Insert the tolloving line ot code to terminate the select statement
done
7. Save the tile, and then close the editor.
8. Make the script executable.
9. Pun the script. See ligure 12-13. 1he menu is displayed shoving the Lnter
choice prompt.
10. Lnter 1 to insert a rov in the tarms database, and then press LntIr. See
ligure 12-13. 1he sqltarmsins script executes prompting you to enter the ID,
name, price, and quantity tor a rov.
11. Lnter the tolloving data 4 tor the ID, MobMlI WatIr S]stIn tor the name,
1000 tor the price, and 3 tor the quantity. See ligure 12-13. Once all the data
is entered, the sqltarmsmenu script displays the Lnter choice prompt again.
12. At the menu prompt, enter a 3 to verity the data has been entered.
13. Nov enter 4 to display the previously entered data. See ligure 12-13. 1he
sqltarmssel script executes and displays the data.
14. Press to quit the sqltarmsmenu script.
13. Close your vindov, and then log out.
1he select sLaLemenL is a builLin shell command. 1o view addiLional inor-
maLion abouL iL, reer Lo Lhe man paes on bash.
502 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
)RLaRcMRK MeRu-baseH ScVMTXs 503
CusXomMzMRK wMXL XLe XTYX CommaRH
You can use the tput command to customize the output ot your terminal.1hus, you can
customize your scripts and customize the output tor your users.You use this command to
initialize a terminal or query the intormation database about a terminal`s capabilities.1he
tIrnMnal capabMlMtMIs MnfornatMon databasI is a database that contains entries about a
terminal and its characteristics.1he database contains characteristics tor each terminal that
is used on the Iinux operating system.1he characteristics are detined in the database vith
various escape sequences specitic to each terminal. 1hey are called escape sequences
because they begin vith the Lsc key. Among other characteristics, a terminal entry usu-
ally includes key sequences tor bolding, underlining, carriage returns, ringing the keyboard
bell, and the tunction keys. Generally, the tormat ot an entry is as tollovs
var1ao1e~name=escae~seguence
Lnderstanding the background behind the var1ao1e~names and escae~seguences
gives you a better understanding ot the tput command.
1ake a look at an example. When you run the graphical portion ot the Iinux operating
system, the system detaults to using the terminal type named xterm tor an X Windovs
terminal. Depending on hov you access the Iinux computer system, your terminal type
may be ditterent. 1his value is stored in an environment variable named TERM. It you
run echo$TERM, your terminal type is displayed. ligure 12-14 shovs the intormation
capabilities tor the xterm terminal type.
*MKuVe 12-13 1he ouLpuL o Lhe sqlarmsmenu scrMpL
12
Lxamine a tev ot the intormation capabilities in the tigure. Notice the variable named
clear on the screen. It has an escape sequence ot \EH\E2J. Note that each \E rep-
resents the Lsc key (or escape sequence, and is used to protect the escape sequence trom
being literally interpreted as H2J. When the terminal receives this escape sequence,
the screen is cleared. Also, notice the escape sequence tor ringing the keyboard bell is
`G tor the variable named bel. 1he caret (`, indicates the Ctrl key. It you press CtrlG,
then the keyboard bell rings. linally notice that the carriage return variable named cr is
equal to `M. It you press CtrlM, it has the same ettect as pressing Lnter.
You can utilize these terminal attributes vith the tput command to do things such as
clear the screen, hide the cursor, place text in specitic positions on the screen, and under-
line or bold text.1here are several vays to run the tput command, but here is the torm
used in this text
tput caname
1his is vhere caname is a terminal capability attribute similar to the ones tound in
1able 12-3.
AXXVMbuXe DescVMTXMoR )xamTle
clear Clears Lhe screen tput clear
bel Rins Lhe keyboard bell tput bel
civis Hides Lhe cursor tput civis
8able 12-5 Some common LermMnal aLLrMbuLes
*MKuVe 12-1 1he MnormaLMon capabMlMLMes o Lhe xLerm LermMnal Lype
Lscape sequence or
rinin Lhe keyboard bell;
Lhe value is `G
Lscape sequence or Lhe
carriae reLurn or LnLer key
bein pressed is `M; Lhe
variable is named cr
Lscape sequence or Lhe
variable named clear. 1he
value is \EH\E2J
50 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
)RLaRcMRK MeRu-baseH ScVMTXs 505
Next you vill create a script that contains a partial menu, but is not completely tunc-
tional as a menu script. It is not completely tunctional because the script only tocuses on
hov you can design a menu using the tput command. lor example, vhen you press 1, there
is no code tor this menu selection. 1he coding is lett tor a later Hands-on Project.
1o crIatI a partMal nInu scrMpt that usIs thI tput connand to sIt tIrnMnal
attrMbutIs
1. Iog in to the Iinux system as a user, and then open a 1erminal emula-
tion vindov.
2. Create a script named tputA in your $HOME/bin directory.
3. Insert the tolloving lines ot code to clear the screen and turn on bolding
tor text
tput clear
tput smso
4. Insert the tolloving line ot code to place the output ot the next statement at
rov 1 and column 0 on the screen. Note that rov 0, column 0, is considered
the upper-lett corner ot the screen, commonly called the home cursor position.
tput cup 1 0
3. Insert the tolloving line ot code to display a message on the screen at posi-
tion rov 1, column 0, on the screen
echo "User $LOGNAME logged on `who [ awk '{print $5}'`"
6. Insert the tolloving lines ot code to place the resulting output ot the date
+%D command at rov 1, column 70
tput cup 1 70
date +%D
AXXVMbuXe DescVMTXMoR )xamTle
cnorm Nakes Lhe cursor appear as normal tput cnorm
cupxy Places Lhe cursor on Lhe screen aL a row speciied by x-, and tput cup l l0
column speciied by ]- coordinaLes sLarLin aL Lhe home
posiLion in Lhe upper-leL corner o Lhe screen
smso 8olds LexL tput smso
rmso 1urns o boldin o LexL tput rmso
smul Underlines LexL tput smul
rmul 1urns o underlinin o LexL tput rmul
sgr0 ReLurns Lhe screen Lo a normal screen (wiLhouL boldin, tput sgr0
underlinin, eLc.)
8able 12-5 Some common LermMnal aLLrMbuLes (conLMnued)
12
7. Insert the tolloving lines ot code to turn ott bolding and place the output ot
the next statement at rov 4, column 23
tput rmso
tput cup 4 23
8. Insert the tolloving line ot code to display the title ot the menu at position
rov 4, column 23, on the screen
echo "The Main Menu"
9. Insert the tolloving lines ot code to place the output ot the next statement at
rov 7 and column 20 on the screen. 1his is the tirst menu item.
tput cup 7 20
echo "1. Employee Information"
10. Insert the tolloving lines ot code to place the output ot the next statement at
rov 8 and column 20 on the screen. 1his is the second menu item.
tput cup 8 20
echo "2. System Functions"
11. Insert the tolloving lines ot code to place the output ot the next statement at
rov 9 and column 20 on the screen. 1his is the last menu item.
tput cup 9 20
echo "9. Exit"
12. Insert the tolloving lines ot code to place the output ot the next statement
at rov 13 and column 20 on the screen and underline the text. 1his is the
prompt.
tput cup 13 20
tput smul
read -p "Enter Selection: " ans
13. Insert the tolloving lines ot code to turn ott underlining ot text and reset the
terminal to a normal screen upon exiting the script
tput rmul
Ztput sgr0
14. Save the tile, and then close the editor.
13. Make the script executable.
16. Pun the script. See ligure 12-13.
17. Press LntIr to reset the terminal and exit the script.
18. Close your vindov, and then log out.
506 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
URHeVsXaRHMRK XLe 6evMsMoR CoRXVol SysXem 507
9ND)6S8ANDIN+ 8H) 6)VISION 'ON86OL 7YS8)M
In a typical programming environment there may be a team ot programmers vorking
on the same project.1he potential tor problems to arise vhen changes are made by dit-
terent programmers to the same scripts at the same time is a reality. lor example, a pro-
grammer named Molly makes a change to a script named tinance. At the same time,
another programmer named Charmita also makes a change to the same script. Whose
changes take ettect It they are using the vi editor, then the last programmer vho saved
the tile and quits the editor has her changes vritten, any previous changes are over-
vritten. Note that this is not a vi-related problem. 1his could occur vith any editor.
So, it Molly and Charmita both vork on the same script concurrently, and they both
make changes, but Molly saves and exits atter Charmita does, then Molly`s changes over-
vrite Charmita`s. All ot Charmita`s vork is lost.
1o handle this situation, the Iinux operating system uses the Pevision Control System.
1he RIvMsMon Control S]stIn (RCS) stores and retrieves multiple revisions ot a script
and resolves contlicts it multiple programmers access the same script concurrently. 1here
are several commands that allov you to manage the changes that occur in a multiple-
access environment such as Iinux. 1hey are listed in 1able 12-6.
*MKuVe 12-15 1he ouLpuL o Lhe LpuLA scrMpL
12
Iook at an example using the ci and co commands trom 1able 12-6.1he ci command
allovs you to check in a script and place it under the control ot PCS. It takes this gen-
eral torm
ci ot1ons f11ename
1his is vhere ot1ons augment the command in some vay, and f11ename is the name
ot the script you vant to add to PCS. So, to check in the script named selA created ear-
lier, you enter
ci selA
Once you executed this command, ci generates a nev tile that includes the tilename
you checked in appended by the suttix ,v.When you run the ci command, the orig-
inal tile no longer exists. It is not deleted, but it is converted into the PCS version. Once
a tile has been checked in, it must be checked out betore it can be used.
ligure 12-16 shovs the ci command used to check in the selA script. In the tigure, the
ls~lselA* command is executed betore and atter the ci command to shov you
that the selA tile existed previously and that selA,v exists atter the ci command execu-
tion. Also, notice in the tigure, an initial revision ot 1.1. A revision number is similar to
a version number tor an operating system.1here are tvo main parts to a revision in PCS.
1hey are the release number and the version, in the tormat r.v. So, revision 1.2 is the
tirst release, second version. In general, revision 1.2 vould have more changes than revi-
sion 1.1 or 1.0 ot a script.
You can use the ~r option, tolloved by the release number, to check in a specitic revi-
sion number ot your script.You can use the ~l (as in lock, option to lock the script so
other programmers cannot make changes to it.When locking an PCS tile, PCS gener-
ates a copy ot the script that can be edited. 1he ~u option unlocks the script so other
programmers can make changes to the script.1he co command is used to check out an
PCS tile.
Next you vill use the PCS commands to vork vith scripts you created earlier in this
chapter.
CommaRH DescVMTXMoR
rcs Chanes Lhe RCS ile aLLribuLes
ci Checks in, or sLores new revisions inLo RCS
co Checks ouL, or reLrieves a revision rom RCS
rlog Displays inormaLion abouL an RCS ile
rcsdiff Compares RCS revisions
rcsmerge Neres RCS revisions
8able 12-6 A ew o Lhe RCS commands
508 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
URHeVsXaRHMRK XLe 6evMsMoR CoRXVol SysXem 509
1o usI RCS connands
1. Iog in to the Iinux system as a user, and then open a 1erminal emula-
tion vindov.
2. Change to the $HOME/bin directory, and then copy sqlfarnsnInu to sIlD
to use a nev copy ot the script.
3. 1o check in and lock the script named selD, type ci~lselD, and then
press LntIr. See ligure 12-17. Notice that three lines are displayed. 1he
~~ is the ci prompt.
4. 1o enter a description, type InitialCheckInby=SYV2EQI, and
then press LntIr. 1he ci prompt is displayed again.
3. 1ype (the period symbol,, and then press LntIr. See ligure 12-17. 1he initial
revision ot 1.1 is displayed, then the text done, indicating that the command
completed, tolloved by the shell prompt.
6. 1o check the tile out, and lock it tor a revision change, type co~lselD,
and then press LntIr. See ligure 12-17. A message indicating the tile is locked
is displayed. Because the tile has been checked out using the lock option, the
selD tile remains. A prompt also asks it you vant to overvrite the tile.
7. 1o make a change to the tile and overvrite selD, type ] and press LntIr.
Note that the text done appears, indicating that the command completed,
tolloved by the prompt.
*MKuVe 12-16 1he ci command
New RCS ile wiLh Lhe
",v" suix
Lo messae
"NodiicaLion by 1odd
Neadors" indicaLes Lhe
chane; Lhe use o Lhe doL
LerminaLes ci
lniLial revision added by
Lhe ci command
12
8. Open sIlD vith vi, and then add these tvo comment lines as the tirst tvo
lines. Be sure to substitute your name and today`s date vhere indicated.
# Author: Your uame
# Date: today's date
9. Save the tile, and then close the editor.
10. 1o check in the tile, lock it, and set the release to 1.2, type ci~r1.2~l
selD, and then press LntIr. See ligure 12-17. 1he ci prompt is displayed
indicating a nev version is being checked in.
11. At the ci prompt, type AddedComments, and then press LntIr. See ligure
12-17. 1he ci prompt is displayed again.
12. 1ype (the period symbol,, and then press LntIr. See ligure 12-17. 1he text
done appears, indicating the command completed. Also, the shell prompt
returns.
13. Close your vindov, and then log out.
%DDIN+ A 7C6I48 AS A 0AUNCHA&L) %44LICA8ION *6OM 8H) +9-
()S/8O4
Iinux allovs you to run a script trom the graphical user intertace desktop. 1he benetit
is that the users do not have to access the shell prompt. Instead, you create a script vithin
*MKuVe 12-17 CheckMnK Mn a Mle, checkMnK ouL a Mle, modMyMnK ML, and checkMnK
ML back MnLo RCS
SLep 10: new version is
checked in
SLep 5: resulLs in revision
number, LexL "done," and
reLurn Lo shell prompL
510 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
AHHMRK a ScVMTX as a LauRcLable ATTlMcaXMoR fVom XLe +UI DeskXoT 511
the shell, and then contigure the script to run vhen a user double-clicks an icon on the
desktop. Next you vill create a script that can be run trom the GLI desktop simply by
double-clicking an icon.
1o crIatI a scrMpt that can bI IIcutId fron thI GUI dIsktop
1. Iog in to the Iinux system as a user, and then open a 1erminal emula-
tion vindov.
2. Pight-click a blank area ot your GLI desktop, and then point to NIv
LaunchIr. See ligure 12-18.
3. Click NIv LaunchIr. 1he Create Iauncher dialog box is displayed as shovn
in ligure 12-19. Notice there are tvo tabs and several text tields vhere you
can enter data.
4. 1ype FarnIrs MInu in the Name text tield, and then press 1ab.
3. 1ype FarnIrs in the Generic name text tield, and then press 1ab.
6. 1ype 1hI FarnIrs MaMn MInu in the Comment text tield, and then
press 1ab.
7. 1ype bMn/sIlD in the Command text tield, and then press 1ab several times
until Pun in 1erminal is highlighted. Note that you are using the selD script
used earlier tor the larmers main menu script. lor a launchable application,
the command`s path begins in your home directory, so you only need to type
binselD.
*MKuVe 12-18 LaunchMnK a new applMcaLMon
12
8. Click Run Mn 1IrnMnal to select it. ligure 12-20 shovs the completed
Create Iauncher dialog box.
9. Click the OK button. An icon named larmers Menu appears on your desktop.
10. Double-click the FarnIrs MInu icon. A terminal vindov opens vith the
script ready tor execution.
11. 1o run the script, type 3, and then press LntIr. See ligure 12-21. A prompt
appears indicating that you can enter an ID to select. 1his is the sqltarmsup-
date script executing. Pemember, this script is coded so it you press Lnter,
then all ot the records are displayed.
*MKuVe 12-20 CompleLed CreaLe Launcher dMaloK box
*MKuVe 12-19 1he CreaLe Launcher dMaloK box
512 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
URHeVsXaRHMRK AHHMXMoRal MaRaKemeRX 8ecLRMques 513
12. Press LntIr to display all the records. See ligure 12-21. 1he records trom the
MySQI database are displayed.
13. Close your vindov, and then log out.
9ND)6S8ANDIN+ %DDI8IONAL 1ANA+)M)N8 8)CHNIQU)S
In this section, you vill learn additional techniques tor script management. 1hese
include the tolloving
Back up and restore
Compression and uncompression
&ack uT aRH 6esXoVe
Because your scripts are stored in a directory on disk and disk tailures do occur, you
need to knov hov to back up and restore your scripts. BackMng up is the process ot
copying your tiles to an alternate location. lor example, it your tiles are stored in one
directory on the hard disk drive, you should consider backing them up to another direc-
tory on another disk. RIstorMng is the process ot bringing the tiles that have been
backed up trom their backed up location to their original location. Although there are
several backup utilities available in the Iinux operating system, here you learn about only
one ot themthe tar command. When you use a backup utility such as tar, the tiles
cannot be utilized until they are restored. 1he tar command places them in a tormat
that only it can interpretnot the shell.
*MKuVe 12-21 1he Farmers Nenu Mcon and Lhe 1ermMnal wMndow
12
1he tar command comes rom Lhe Lerm 1ape Archive. lL was oriinally
inLended Lo be used wiLh sequenLial Lape meLhods.
1he tar command takes the tolloving general torm
tar ot1ons f11ename1, f11ename2,.
Although the tar command has many options, only a tev are discussed here. 1able 12-7
shovs a description ot some ot the options.
Next you vill use the tar command to back up the sqltarmsdel, sqltarmsins, sqltarmssel,
and sqltarmsupdate scripts created tor larmers, Inc.
1o run thI tar connand to backup, vIrMf], and rIstorI fMlIs
1. Iog in to the Iinux system as a user, and then open a 1erminal emula-
tion vindov.
2. Change to the bMn directory.
3. 1o back up the scripts using the tar command, type tar-cvf
farmbackup.tar sglfarms*, and then press LntIr. 1he command
displays the tiles that are backed up. Note that the name tarmbackup.tar is
the name ot the tile containing the backed up script tiles. Although not
required, the tar extension indicates the tile is a tar backup. 1he use ot the
asterisk as a vildcard symbol in sqltarms causes all tiles beginning vith
sqltarms to be backed up.
1he Lar backup ile is someLimes called a Lar archive or a "Larball" because all
o Lhe iles are rolled up inside o one ile.
4. 1o verity that the tar command vorked correctly, type tar-tvf
farmbackup.tar, and then press LntIr. 1he tiles in the tar tile are displayed.
See ligure 12-22.
3. Pemove the tour script tiles.
OTXMoR DescVMTXMoR
~c CreaLes a tar archive ile
~v Displays more inormaLion as tar execuLes (Lhe "v" sLands or verbose)
~ff11ename Speciies Lhe tar backup ile name
~t Shows a Lable o conLenLs or Lhe iles in Lhe tar archive ile
~r ResLores iles wiLhin Lhe tar archive ile
8able 12-7 A ew tar command opLMons
51 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
URHeVsXaRHMRK AHHMXMoRal MaRaKemeRX 8ecLRMques 515
6. 1o restore the tour script tiles, type tar~xvf farmbackup.tar, and then
press LntIr.
7. Iist the tiles to prove they have been restored. See ligure 12-22.
8. Close your vindov, and then log out.
AlLhouh in Lhese exercises you are backin up Lo a ile on disk, Lypically you
back up and resLore much larer amounLs o daLa and use some Lype o
removable media such as maneLic Lape, exLernal hard drives, or CD-RONs.
ComTVessMoR aRH URcomTVessMoR
ConprIssMon is the process ot saving disk space by removing the repeating portions ot
a tile in order to make it smaller. You cannot use a tile vhen the tile is compressed
because a compressed tile is in a special tormat. In order to vork vith a compressed tile,
the compressed tile must be uncompressed. UnconprIssMon is the process ot returning
a compressed tile into its original state. Compression varies based on the amount ot data
that is duplicated and the compression algorithm used. At times, compression can yield
betveen a 73 to 90 savings. You generally compress a tile that is to be dovnloaded
over the Internet. Because it is smaller, it takes less time to dovnload a compressed tile.
Hovever, in order to utilize the tile, you must uncompress it. In Iinux, you can use the
gzip command to compress a tile and the gunzip command to uncompress a tile. Next
you vill explore hov to compress and uncompress tiles using the sqltarmsins tile tor
larmers, Inc.
*MKuVe 12-22 DemonsLraLMnK Lhe use o Lhe tar command Lo back up, verMy, and resLore
SLep 4: iles in Lhe Lar ile
SLep 7: resLored iles are
displayed
12
1o conprIss and unconprIss a scrMpt
1. Iog in to the Iinux system as a user, and then open a 1erminal emula-
tion vindov.
2. Change to the bMn directory.
3. 1o list the sqltarmsins tile, type ls~lsglfarmsins, and then press
LntIr. 1his step is done so you can compare the uncompressed and com-
pressed torms ot the tile.
4. 1o compress the tile named sqltarmsins, type gzipsglfarmsins, and then
press LntIr. See ligure 12-23.
3. 1o list all the tiles beginning vith sqltarmsins, type ls~lsglfarmsins*,
and then press LntIr. 1he original tile has been removed. In order to utilize
the original tile, the .gz tile must be uncompressed.
6. 1o uncompress the tile named sqlfarmsins, type gunzip
sglfarmsins.gz, and then press LntIr. See ligure 12-23.
7. 1o list all the tiles beginning vith sqltarmsins, type ls~lsglfarmsins*,
and then press LntIr. Notice the original tilename appears.
8. Close your vindov, and then log out.
*MKuVe 12-23 1he use o compressMon and uncompressMon
SLep 5: ile now has a .z
exLension
516 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
CVeaXMRK CusXom MaRual 4aKes 517
You can use Lhe ~z opLion on Lhe tar command Lo compress Lhe Lar
backup ile. For example, Lo compress and back up all o Lhe sqlarms scripLs
Lo a backup ile named armbackup.z usin tar, you use tar~czvf
farmbackup.gz sqlfarm*. 1o veriy Lhe compressed Lar ile you use
tar~tzvffarmbackup.gz. 1o resLore Lhe compressed Lar ile, you use
tar~xzvffarmbackup.gz.
'6)A8IN+ 'US8OM 1ANUAL 4A+)S
Atter you create your scripts, you should create manual pages tor them. 1his vay users
can reviev the manual pages tor your application just as they can reviev the manual
pages tor an operating system command. When you create manual pages, a decrease in
support time by the computer statt most likely results, thereby alloving the statt time tor
other duties. 1he manual pages use a document-tormatting command named groff.
When creating a manual page tor your script, you can use an editor such as vi, but you
must vrite the manual page using the groff language statements. A manual page is typ-
ically composed ot a preamble tolloved by sections. A prIanblI is the tirst line ot text
prior to the sections, it is like a header line presenting general intormation about the
manual page. 1he groff command used to identity the preamble is .TH. It takes the
tolloving general torm
.TH t1t1e sect1on date source manua1
1he t1t1e is the title ot the manual page, the sect1on is the category number ot the
manual page to vhich the command belongs, the date is the revision date, the source
is trom vhere the manual page originated, and the manua1 is the title ot the manual
page. Note that sect1on here is a number that represents the type ot manual. Most user
commands are in section number 1.
A sIctMon ot the manual page is a body ot text identitying a specitic area ot the man-
ual page such as the NAML, SYNOPSIS, DLSCPIP1ION, OP1IONS, lIILS, SLL
AISO, DIAGNOS1ICS, BLGS, and AL1HOP.1his ditters trom sect1on in the pre-
vious syntax, vhich is a category number. Note that the NAML section is required, you
need to tollov it vith a one-line description. You have seen these sections vhen you
have executed the man pages tor an operating system command.1he groffcommand
to create a section in a manual page is .SH. It takes the tolloving general torm
.SH name
When creaLin a manual pae or a scripL, you need Lo append ".1" Lo Lhe
end o Lhe ilename. For example, Nenu.1 works; Nenu doesn'L.
Next you vill create a manual page tor the larmers Main Menu that you created earlier
in this chapter.
12
1o crIatI a nanual pagI for thI FarnIrs MaMn MInu
1. Iog in to the Iinux system as a user, and then open a 1erminal emula-
tion vindov.
2. 1o create the manual pages, create a tile named FarnIrs1.
3. 1o create the preamble, insert the tolloving line ot code
.TH Farmers "1" "November 2004" "Farmers 1.0"
4. 1o create the NAML section, insert the tolloving lines ot code
.SH NAME
Farmers - The Farmers Main Menu
3. 1o create the SYNOPSIS section, insert the tolloving lines ot code. Note
the .B command is used to bold the text tolloving it. 1he synopsis is
sqltarmsmenu, this indicates hov you run the command associated vith
this manual page. In this case, to run the command you simply enter
sqlfarmsmenu at the shell prompt.
.SH SYNOPSIS
.B sglfarmsmenu
6. 1o create the DLSCPIP1ION section, insert the tolloving lines ot code.
Note the .PP command is used to begin a nev paragraph.
.SH DESCRIPTION
The Farmers main menu consists of the following menus
.PP
1} Insert a record in the database
.PP
2} Delete a record from the database
.PP
3} Select records from the database
.PP
4} Update a record from the database
.PP
5} Quit the Farmers Main Menu
7. 1o create the AL1HOP section, insert the tolloving lines ot code. Make
sure you substitute your ovn name.
.SH AUTHOR
Written by =SYVj2EQI.
8. Save the tile, and then quit the editor.
9. 1o viev your manual page tor larmers, Inc., type groff~Tascii~man
Farmers.1[more, and then press LntIr. Note the ~Tascii option
means to display the text in ASCII. 1he ~man option means to display the
page named larmers.1. ligure 12-24 shovs this command executing.
10. Close your vindov, and then log out.
518 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
CLaTXeV SummaVy 519
ln order Lo view your manual paes usin Lhe man command, you should
copy your manual pae in compressed ormaL Lo Lhe /usr/share/man/man1
direcLory. You musL have rooL access Lo place your manual paes in Lhis direcLory.
l you do, compress Farmers.1, and Lhen copy Farmers.1.z Lo /usr/share/
man/man1. 1o view your manual paes as parL o Lhe man command, you
Lype man Farmers.
'HA48)6 7UMMA6Y
You can use a Web brovser to access Web page scripts over an intranet or the
Internet. A Web client requests Web pages trom a Web server. 1he Web client and
Web server transter Web pages using the H11P protocol. A Web server is a com-
puter system running Web hosting sottvare such as Apache. Web page scripts are
stored and executed in the varvvvcgi-bin directory.
1he Iinux operating system uses the MySQI sottvare to manage databases. A data-
base consists ot one or more tables tor storing data. A table consists ot data stored in
rovs and columns. A rov is similar to a record and a column is similar to a tield.
Database management sottvare provides greater control ot the data than simply
accessing the data vithin a text tile.
You can create scripts that intertace vith MySQI. 1he basic MySQI statements are
insert, delete, select, and update. Insert allovs you to add data into a rov. Delete
allovs you to remove data trom a rov. Select allovs you to list data in a rov.
Lpdate allovs you to modity data vithin a rov.
*MKuVe 12-2 Nanual paKes you NusL creaLed
12
You can enhance your menu-based scripts by using the tput and select commands.
1he tput command allovs you to contigure the characteristics ot the display terminal.
lor example, you can bold or underline text in a script using this command. 1he
select command is explicitly vritten to create menus. It is similar to a case
statement vith a looping mechanism.
Because Iinux is a multiuser operating system, multiple programmers can modity
the same script at the same time. Any changes made by the programmer vho saves
the script tirst can be lost by the programmer vho saves the script last. 1o rectity
this problem, Iinux uses the Pevision Control System (PCS, to keep track ot
changes made by programmers. PCS uses the ci command to check in a script
revision and the co command to check out a script revision.
You can create a script that can be launched trom the desktop alloving users to
avoid going to the shell prompt to run a command. Lsers can simply double-click
an icon on their desktops. Once clicked, the script associated vith the icon executes
in a separate terminal vindov.
Your scripts are stored in a directory on a hard disk drive. Because hard disk drives
occasionally maltunction, you should consider backing up your script to another
device such as a tloppy or tape. Pestoring is the counterpart ot backing up.You
restore your scripts to their original locations it the hard drive does indeed
maltunction. 1he tar command can be used to back up and restore scripts or
other tiles. Additionally, you can compress your scripts in order to save disk space.
A script, or other tile, that is compressed cannot be used unless it is uncompressed.
1he gzip command is used to compress and the gunzip command is used to
uncompress.
Once your scripts have been created, you should create manual pages tor them. 1his
provides the user vith the ability to reviev the documentation at any time result-
ing in a decrease in the need tor technical support. 1he groff command is used to
tormat and process the manual pages. A manual page consists ot the preamble and
sections. 1he preamble is the tirst line betore any section. 1he preamble presents
general intormation about the manual page. Sections identity specitic parts ot the
manual page. 1he required section is NAML.
6)VI)W 5U)S8IONS
1. Which ot the tolloving does a Web server use to torvard Web pages to a Web client
a. IP
b. DNS
c. H11P
d. CGI
520 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
6evMew QuesXMoRs 521
2. A(n, is a code statement used in a Web page.
a. Web server
b. H1MI tag
c. IP address
d. MySQI database
3. A database is like a record in a text tile.
a. rov
b. column
c. table
d. tag
4. 1he tolloving H1MI code statement is used to terminate the horizontal line
statement in an H1MI document.
a. </HR>
b. <HR>
c. <\HR>
d. </HR/>
3. A database is like a tield in a text tile.
a. rov
b. column
c. table
d. tag
6. 1he tolloving H1MI code statements that are used to identity the beginning and
ending ot the H1MI code vithin a document are .
a. <CENTER> and </CENTER>
b. <HEAD> and </HEAD>
c. <HTML> and </HTML>
d. <BEGIN> and </END>
7. 1he directory location on the Web server vhere you should place your Web page
scripts tor execution over a netvork is .
a. /www/var/cgi~bin
b. /usr/local/bin
c. $HOME/var/www/cgi~bin
d. /var/www/cgi~bin
12
8. 1he option is used to create a tar archive tile.
a. ~c
b. ~x
c. ~f
d. ~t
9. 1he command is used to create the preamble in a manual
page.
a. .B
b. .SH
c. <PRE>
d. .TH
10. 1he command is used to create a section in a manual page.
a. .PP
b. .SH
c. <SECTION>
d. .TH
11. 1he H1MI code to preserve the pretormatted output ot a command is
.
a. <OUTPUT>
b. <PRE>
c. <POST>
d. .TH
12. 1he MySQI statement to add data to a table is .
a. select
b. put
c. add
d. insert
13. 1he command to compress a tile is .
a. gunzip
b. tar~t
c. ci
d. gzip
522 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
6evMew QuesXMoRs 523
14. 1he command to check a tile into PCS is .
a. tar
b. rlog
c. co
d. ci
13. 1he MySQI statement to viev data in a table is .
a. select
b. update
c. show
d. echo
16. 1he command to check a tile out ot PCS is .
a. tar
b. rlog
c. co
d. ci
17. 1he manual page section that is required is .
a. SYNOPSIS
b. PPLAMBIL
c. SLL AISO
d. NAML
18. 1he command to initialize terminal characteristics is .
a. select
b. tput
c. ci
d. print
19. 1he command to create a menu in the shell is .
a. select
b. tput
c. for
d. case
20. 1he command to modity a column vithin a database is .
a. place
b. update
c. modify
d. insert
12
,ANDSON 46OJ)C8S
4VoNecX 12-1
In this project, you vill create a Web page script that displays a list ot processes and the date.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named ProNIct12-1 in the HOME/bin directory.
3. Include the necessary code to create a Web page script that displays a list ot
processes and the current date. Be sure to include a heading line indicating that
the Web page is displaying a list ot processes.You also need to bold and center this
line as vell as use a heading level 1 tor it. Lse a heading level 2 tor the output ot
the process listing and date. Preserve the pretormatted output ot the commands.
4. Save the tile, and then close the editor.
3. Copy this Web page script or have it copied to the correct directory tor vieving
in a Web brovser.
6. Viev and print this Web page script in a Web brovser.
7. Close your vindov, and then log out.
4VoNecX 12-2
In this project, you vill create a Web page script that runs a second script. 1he second
script is used to display the contents ot a tile. When you access the Web page script, it
runs the second script, and the output ot the second script appears in the Web brovser
display area.You need to use the payroll tile shovn in 1able 10-8 trom Project 10-8 to
complete this project.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. It you have not created the payroll tile used in 1able 10-8, do so nov.
3. Create the shell script that displays the records tirst. Name this script ProNIct12-2A,
and place it in the HOME/bin directory.
4. Write the necessary code statements to read the contents ot the payroll tile and
display the records on the screen.
3. Save the tile, close the editor, make the script executable, and test the script. Be
sure the records are displayed betore proceeding to the next step.
6. Copy ProNIct 12-2A to the /var/vvv/cgM-bMn directory.
7. Create the Web page script that executes the script named Project12-2A. Name
this script ProNIct12-2, and place it in the HOME/bin directory.
8. Be sure the Web page script displays the server address and script name vithin the
Web page. lor the title ot the Web page, use Lmployee Peport. lor the heading,
use Payroll Peport. Make sure the heading is centered, and has a heading level ot
2. Preserve the pretormatted output ot the commands. Insert the proper code to
execute Project 12-2A. (HintYou may need to give the tull path.,
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
52 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
HaRHs-oR 4VoNecXs 525
9. Copy ProNIct 12-2 to the /var/vvv/cgM-bMn directory.
10. Copy the pa]roll tile to the /var/vvv/cgM-bMn directory.
11. Viev and print this Web page script in a Web brovser.
12. Close your vindov, and then log out.
4VoNecX 12-3
In this project, you vill vork vith a partner to practice using the PCS commands. 1he
goal is to help you understand hov PCS vorks.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a directory in root named RCS, and assign permissions ot read, vrite, and
execute tor all users.You may need to have your instructor pertorm this step.
3. Copy the sqlfarnsnInu tile to this directory as sqlfarnsnInu\\\. Note xxx
are your initials tor this and subsequent steps.You may need to have your instructor
pertorm this step.
4. Change directory locations to the PCS directory.
3. 1o check in the sqltarmsmenuxxx tile and lock it, type ci~lsglfarmsmenu\\\,
and then press LntIr.
6. 1ype Initialcheckinby\\\, and then press LntIr.
7. 1o terminate the ci command, type (a period,, and then press LntIr.
8. Ask your partner to log in and change to the PCS directory.
9. 1o attempt a check out on the locked tile, your partner should type this command
co~lsglfarmsmenu\\\. Be sure your partner uses your initials.
10. Pecord your results.
11. Close your vindov, and then log out.
4VoNecX 12-
In this project, you vill create scripts that access rovs in a database.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Have someone log in as the root user, and then create a database named paydb.
Also, have someone create a table named paytable vithin paydb vith the tolloving
tields ID as an integer ot tvo positions, Name vith 23 characters, Pate as an
integer ot tvo positions, and Hours as an integer ot tvo positions.
3. Have someone log in as the root user to create, and then assign the appropriate
MySQI permissions to insert, delete, update, and select data.
4. Have someone log in as the root user to reload MySQI.
3. Create a shell script named sqlpa]Mns in the HOME/bin directory that allovs the
user to insert data into the paytable. 1he user inserts data based upon the ID.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
12
6. Save the tile, close the editor, and then make the script executable.
7. Pun the script, and then insert the data shovn in 1able 12-8.
8. Create a shell script named sqlpa]dIl in the HOME/bin directory that allovs the
user to delete data in the paytable. 1he user deletes data based upon the ID.
9. Save the tile, close the editor, and then make the script executable.
10. Pun the script, and then delete record 4.
11. Create a shell script named sqlpa]sIl in the HOME/bin directory that allovs the
user to select data in the paytable. 1he user selects data based upon the ID. Allov
the user to press Lnter to select all rovs.
12. Save the tile, close the editor, and then make the script executable.
13. Pun the script, and then list all the rovs.
14. Create a shell script named sqlpa]updatI in the HOME/bin directory that allovs
the user to update data into the paytable. 1he user updates data based upon the ID.
Allov the user the ability to update hours only.
13. Save the tile, close the editor, and then make the script executable.
16. Pun the script tor ID 2, and update the hours to 37.
17. Verity your tindings by running the sqlpa]sIl script.
18. Close your vindovs, and then log out.
4VoNecX 12-5
In this project, you vill create a menu tor Project 12-4.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named sqlpa]nInu in the HOME/bin directory.
3. Save the tile, close the editor, and then make the script executable.
4. Lse the select statement to allov the user to press 1 to insert, 2 to delete, 3 to
select, and 4 to update rovs in the database. It the user presses 3, exit the script.
3. Pun the script.
6. Close the vindov, and then log out.
,ERHWSR
4VSNIGX
)mTloyee ID Name 6aXe HouVs
1 Liam NonLa 30 39
2 Susan Gonzalez 40 40
3 Dave DusLsLanz 38 33
4 Lou LllensLein 44 43
8able 12-8 Lmployee records
526 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues
HaRHs-oR 4VoNecXs 527
4VoNecX 12-6
In this project, you vill create a launchable application tor Project 12-3.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a launchable application that can be accessed by double-clicking an icon
on the desktop.
3. Complete tields such as Name, Generic Name, Comment, and Command. Also
make sure you check the Pun in 1erminal option. lor Name, enter Pa]roll. lor
Command, enter bMn/ProNIct12-.
4. Pun the launchable application by double-clicking the icon associated vith it.
3. Close the vindov, and then log out.
4VoNecX 12-7
In this project, you vill create scripts to back up, restore, and verity the script tiles you
created in Project 12-4 and the menu script you create in Project 12-3.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a shell script named ProNIct12-7 in the HOME/bin directory.
3. Lse a select statement to allov the user to press 1 to back up the sqlpay tiles,
2 to verity the tiles have been backed up, and 3 to restore the sqlpay tiles. It the
user presses 4, exit the script.
4. Save the tile, close the editor, and then make the script executable.
3. Pun the script, and enter 1, and then press LntIr to back up the tiles and record
the output.
6. Pun the script, enter 2, and then press LntIr to verity the tiles and record the output.
7. Lxit the script, and then remove the sqlpa]" tiles.
8. Perun the script, enter 3, and then press LntIr to restore the tiles and record
the output.
9. Quit the script, close your vindov, and then log out.
4VoNecX 12-8
In this project, you vill create a manual page tor the sqlpaymenu script you created in
Project 12-3.
1. Iog in to the Iinux system as a user, and then open a 1erminal emulation vindov.
2. Create a tile that contains manual page code named ProNIct12-8 in the
HOME/bin directory.
3. Lsing the larmers.1 manual page as a guide, create a manual page tor the sqlpay-
menu script.
4. Save the tile, and then close the editor.
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
,ERHWSR
4VSNIGX
12
3. Display the script using the groff command.
6. Compress the script.
7. Copy the tile or have someone vith root access copy the compressed tile (vith
the .gz extension, to the /usr/sharI/nan/nan1 directory.
8. 1o run the man page command tor your script, type nan ProNIct12-8.
9. Close your vindov, and then log out.
'AS) 46OJ)C8S
Case 12-1
1MI needs help vriting an application comprising several scripts. Here are the require-
ments.You need to complete all the projects in this chapter tirst.
1. lirst, a main script is needed that can run the other scripts. On this main menu
script, the user needs to be able to enter 1 tor accessing Lmployee Intormation,
2 tor accessing System lunctions, and 9 to Lxit. Lse appropriate heading levels
and code at least tvo terminal characteristic statements. Lse the trap command to
display a message vhen the user presses CtrlC.
2. lor the Lmployee Intormation script, run the sqlpaymenu trom Project 12-3.
Because this is a complete module, it runs as it did in Project 12-3.
3. lor the System lunctions script, require the user to enter a passvord. 1est tor the
passvord ot zorro13. Suppress passvord entry. It a user enters the correct passvord,
run the script paybackupmenu trom Project 12-7. Because this is a complete
module, it runs as it did in Project 12-7.
4. Create the script as a launchable application.
Case 12-2
McDoogland`s Candy Store needs a menu script that allovs the user to
1. Press 1 and enter a tilename to back up.
2. Press 2 to verity the backup.
3. Press 3 to restore the backed up tile.
4. Press 4 to enter a tilename to compress.
3. Press 3 to enter a tilename to uncompress.
6. Press 6 to enter a tilename to check in to PCS as locked.
7. Press 7 to enter a tilename to check out ot PCS as locked.
8. Press 8 to quit.
Also, McDoogland`s requires that the script can be accessed by double-clicking an icon
on the desktop.
'EWI
4VSNIGX
'EWI
4VSNIGX
528 CLaTXeV 12 ScVMTX DesMKR aRH MaRaKemeRX Issues

You might also like