Linux Shell Script Entire Ebook
Linux Shell Script Entire Ebook
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: [email protected].
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
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
()'-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
-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