eeeBook
CollectionLinuxShellScriptEntireEbookThisisaProtectedPDFdocument.Pleaseenteryourusernameandpasswordtounlockthetext.
Remembermyusernameandpassword.IfyouareexperiencingproblemsunlockingthisdocumentoryouhavequestionsregardingProtectedpdffilespleasecontactaTechnicalSupportrepresentative:IntheUnitedStates:1-877-832-4867InCanada:1-800-859-3682OutsidetheU.S.andCanada:1-602-387-2222Email:[email protected]',%48)6
-2863(9'8-32838,)34)6%8-2+7=78)1)2:-6321)28-RXLMWGLETXIV]SY[MPP9RHIVWXERHSTIVEXMRKW]WXIQW(IJMRIXLI9RM\ERH0MRY\STIVEXMRKW]WXIQW9RHIVWXERHGPEWWMJMGEXMSRWSJWSJX[EVI9RHIVWXERHHEXE9RHIVWXERHXLIYWIVVSPIW9RHIVWXERHFEWMG0MRY\GSQQERHW'VIEXIWLIPPWGVMTXW8he
operating system is a set ot sottvare instructions that run the
com-puter. Whenyouvriteshellscr iptprograms,
youcombineIinuxoperating system commands and programming logic to
create automatedtasks. In this chapter, you vill learn about the
major operating systems
asvellasteaturesspecitictotheIinuxoperatingsystem.
YouvilllearnaboutthetypesotusersinaIinuxenvironment,
vhichvillhelpyoudeterminethetypeotaccessandtypeotscriptsindividualsneed.
SomeotthecommonbasicIinuxcommandsvillbediscussed. Youcanusethese
commands in scripts to make a user`sjob easier. linally, to get
youstarted vith shell programming, you vill create a tev shell
scripts.9NDRS1ANDING3PRA1ING7YS1MSSoftvareisasetotinstructionsthatareprocessedbythecomputersystem.
1heoperating systen is sottvare that governs computer systems. 1he
components in acomputer 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 allovsyou to save a
tile to disk, retrieve a tile trom disk, run a spreadsheet
application, printa tile, compile a program, point and click vith
your mouse, enter text commands, ornavigate 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 betveenthe operating system and the other components
in a computer
system.1heLerms"soLware"and"prorams"aresynonymousinLhecompuLerindusLry.8MTHardware
ComponentsOperaLin sysLemDisk drives Keyboard NoniLor Nouse PrinLer
Processor RAN(memory)Users ApplicaLionsfIgure 1-1 Role o Lhe
operaLin sysLem2 Chapter 1IntroductIon to the OperatIng System
nvIronmentUnderstandIng OperatIng Systems 31here are many ditterent
operating systems running many ditterent computer systems
bothtorbusinessandhomeuse.
Operatingsystemsrunlargemaintramecomputers, 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
maintramecomputersandaregenerallyusedinlargecorporations.
Anexampleotamaintrameoperating system is the IBM Multiple Virtual
Storage (MVS,
system.Netvorkoperatingsystensallovcomputerstoshareresourcesoveranetvork.
Aresource is a hardvare device, a sottvare program, or a tile. A
printer that can be used bymultiple users is an example ot a shared
resource. In the past a netvork vas detined as agroup ot computers
and printers connected by cables. Hovever, vith the advent ot
nevertechnology,
computersandprinterscancommunicateviavirelesstransmissionasvell.Netvorkoperatingsystemsuseprotocol
softvaretotacilitatethecommunicationamongcomputersthroughoutanetvork.
1CPIPisthemostcommonprotocolusedtoday. 1ransnission Control
Protocol/Internet Protocol (1CP/IP) allovs you toconnect 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 vithothercomputersonthenetvork.
1hehostmayalsohaveaDonainNaneService(DNS) nane such as
Pedhat.com.1his is sometimes called its triendly name.1he DNSname
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`sshared resources. Clients are the
computers that use the resources made available by theservers.
1heclient/server modelis vhen aserver computerhandlestherequests
madeby the client computer.1here are usually more clients than
servers in a netvork. Becausethe 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 systemsthat run on servers are Novell NetWare, Microsott
Windovs N1 Server, 2000 Server, andLNIXIinux. Windovs93, Windovs98,
WindovsN1 Workstation, Windovs2000Protessional, and Windovs XP are
examples ot client operating systems.You can also runLNIXIinux 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
useotacommonprotocolallovscommunicationtooccur. Inligure1-2,
youcanseetheserver and clients in a netvork environment.1(fINING
1H9NIX
AND0INUX3PRA1ING7YS1MS1heLNIXoperatingsystemgoesbacktothe1960s.
SeveralemployeesvorkingtorA181 developed an operating system based
on the C language and called it LNIX.1heinitial version vas called
A181 System Pelease V.1he operating system code vas
treelydistributed to major universities vhere changes vere made to
it. So, unlike proprietaryoperating systems such as Microsott
Windovs, Novell, and IBM, a single vendor has notdevelopedLNIX.
1herehavebeennumerousversionsottheinitialoperatingsystem,and many
vendors have customized LNIX to tit their ovn plattorms. IBM has
vrittena version ot LNIX called Advanced Interactive Lxecutive
(AIX,, Sun has vritten Solaris,andHevlett-PackardhasvrittenHP-LX,
andtherearemanyothers. Pecently,
sott-varevendorsvhohavetraditionallydevelopedtheirovnoperatingsystemstortheirovn
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-1shovs a listing
ot some ot the versions ot the Iinux operating system and the
associatedWeb sites tor researching them. 1his book tocuses on the
Iinux operating system.ClienL compuLer ClienL compuLer ClienL
compuLerServer compuLerfIgure 1-2 ClienL/server model in a neLwork4
Chapter 1IntroductIon to the OperatIng System nvIronmentDefInIng
the UnIx and LInux OperatIng Systems 5Iet`s look at some ot the
teatures the Iinux operating systems otters.1hey are as
tollovsMultiuser capabilityPortability MultitaskingAbility to use
multiple processorsMultiple modes ot operationMultIuser CapabIlItyA
nultiuser operating system is one capable ot handling multiple
requests by a varietyot users. Manycompanies run Iinux as their
mainstay operating system tor their busi-ness because it provides a
multiple user plattorm. 1hey can install their applications ona
Iinux server and have client computers access the application on
the server over thenetvork. Some operatingsystemsare
single-userplattorms(onlyoneuser canusethecomputer,, such as
Windovs 93 and 98.A plaLorm comprises boLh Lhe hardware and soLware
combinaLion on which aiven sysLem runs. For example, i Linux
version 8.0 is Lhe soLware runnin onan lnLel-based hardware sysLem,
Lhen Lhe Lwo combined are called Lhe plaLorm.PortabIlItyPortability
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 donebecause installing an operating
system can be an arduous task. Many operating systemsare vritten
tor a specitic processor. Lach processor has its ovn instruction
set, vhichis the set ot instructions the processor uses to operate.
1heinstruction setsot ditterentprocessors are typically not
compatible.You can think ot an instruction set as being thelanguage
specitic to the processor.8MTVersIon Web SIteDebian
www.debian.orOpenLinux www.calderasysLems.comSuSe
www.suse.comSlackware www.slackware.comNandrake www.mandrake.comRed
HaL www.redhaL.com1able 1-1 Versions o Linux and Lheir Web
siLes11here 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
hardvaretopertormthetasksnotprovidedbytheinstructionset. Becauseot
theenhancedhard-vare, a PISC processor is taster, yet more
expensive, than a CISC processor.1he processorin 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 Iinuxoperating system gives you more hardvare options on
vhich to run the operating systembecause you can choose to run
Iinux on either type ot processor.MultItaskIngMultitasking is vhen
the operating system can handle multiple jobs at seemingly the
sametime. When a program executes, it is knovn as a job or process.
1echnically, the operatingsystem 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-robinmanner. Iet`slookatanexample.
Assumetheoperatingsystemgiveseachjobonlyoneminute 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, thenthe system can retrieve the
next job in the process queue or continue processing the tirstjob
that vas sent to the svap tile. 1his is done tor all jobs until
there is no more vork tobedone.
1headvantageotthisisthatonelargejoblasting13minutesorsovon`tslovdovn
the vhole system and keep smaller jobs that require less processing
time trom beingcompleted.1he Iinux operating system employs
preemptive multitasking as opposed to cooperativemultitasking.With
preenptive nultitasking, the operating system has the ability to
takecontrol ot the system trom an application. With cooperative
nultitasking, the applica-tion takes control ot the system
resources.1he advantage ot preemptive multitasking is thatit an
application tails, the vhole system von`t necessarily crash. In
cooperative operatingsystems, a tailed application can cause the
vhole computer to treeze or crash.AbIlIty to Use MultIple
Processors1heabilitytohaveseveralprocessorstoimproveoverallthroughput,
ortheamountotvork 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 usesnultithreadingvhich 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 1IntroductIon to the OperatIng System
nvIronmentDefInIng the UnIx and LInux OperatIng Systems
7Synnetrical nultiprocessing (SMP) tacilitates multithreading. SMP
greatly
enhancesthroughputbecauseseveralprocessorshandleonelargetaskinsteadotasingleprocessorhandling
the same task alone. SMP is typical on systems vith a large number
ot users vherethroughput demands are great.MultIple Modes of
OperatIon 1he Iinux operating system operates in tvo modes. 1hey
are as tollovsGraphical user intertace (GLI,1ext
GraphIcalUserInterface(GUI)Mode1he 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
toolsyou need to pertorm daily tunctions. Some ot the tools
provided as part ot the desktopareaGLItilemanager,
aDesktopmanagerandanInternet Webbrovser. ligure1-3shovs a
screenshot ot the Iinux Gnome desktop.Linux also ives you access Lo
Lhe lnLerneL by uLilizin Lhe necessary hardwareLo run NeLscape
CommunicaLor, Web browser soLware, and 1CP/lP.8MTfIgure 1-3 1he
Linux Gnome deskLopOpens Lhe Gnome menuWeb browser1ligure 1-4 shovs
a screen shot ot the Iinux tile manager open on the desktop.1ext
ModeIinux also provides you vith a text mode intertace. In this
intertace you use commandsto navigate the Iinux system and vrite
your shell scripts. You villneed to use text
orgraphicaleditorstovriteshellscriptprograms.
ligure1-3shovsascreenshotottheIinux text mode open on the desktop
ot the GLI.fIgure 1-5 Linux LexL modefIgure 1-4 Linux ile manaer8
Chapter 1IntroductIon to the OperatIng System
nvIronmentUnderstandIng ClassIfIcatIons of Software 9You 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 commandor 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 Iinuxare listed in 1able
1-2.9NDRS1ANDING'LASSIfICA1IONSOf7Of1WARIt is alvays a good idea to
knov vhat sottvare is running on your system.1his vay, youare
better equipped to troubleshoot in case a problem occurs. Also,
sottvare can be undera sottvare contract, so you may be able to
contact someone it problems arise.Sottvare is divided into the
tolloving categoriesSystem sottvare Application sottvareSystem
SoftwareSystemsottvareincludesthecorecomponentsotthesystemthatmustbepresentinorder
tor the computer to operate. Lxamples ot system sottvare are1he
kernelob management sottvareMemory management sottvareProgramming
languagesDevice driversSottvare utilitiesShell Name DescrIptIonsh
1he oriinal shell wriLLen by SLeven 8ourne, also known as Lhe
8ourne Shellbash Publicly licensed 8ourne-Aain Shell compaLible
wiLh Lhe oriinal 8ourne Shell;Lhis is Lhe deaulL shell you eL aL
loincsh C-shell which uses a C-like synLaxksh Publicly licensed
Korn shell wriLLen by David Korn1able 1-2 Various shell
inLerpreLers available on Linux11hekernel1he kernel is the heart ot
the operating system.When any computer system boots, a setot
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 anyoperating
systemthatoccupiesmemory aslongasthe computer remains on. It
controlsall other sottvare activity. Only the most important and
videly used programs are part otthe kernel.1he kernel calls upon
other programs that are held on disk or in other areas otmemoryby
intertacingvithother operatingsystemprogramsvith thehardvare ot
thecomputer system. Most operating systems have a kernel that
remains in memory. Lxamplesinclude 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 roma 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 teaturessuch as the ones shovn in ligure
1-6.JobManagement 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 LhesysLem prorams are
jobs run as daemons.8MTfIgure 1-6 Kernel eaLures you can
cusLomize8MT10 Chapter 1IntroductIon to the OperatIng System
nvIronmentUnderstandIng ClassIfIcatIons of Software 11Prior to job
execution, a job is placed in a job process queue. A job process
queue isaholdingareatorthejobvhileitvaitsitsturntorexecution.
ArunningprocesshasCPLandmemoryresources boundtoit.
1heIinuxoperating systemusesa processtree 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-nalpurposesbytheoperatingsystem.
1heoperatingsystemusesthePIDvhencommunicatingviththeprocess.
1heprocessnameismuchlikeyourovnnameandthe PID is much like your
Social Security number.Lachprocess is created trom a parent. Iinux
uses the termspavning to describeoneprocess starting trom another.
At times, a process may encounter problems causing it toconsume
excessive CPL time or to become orphaned. lor instance, it process
A spavnsprocessB, thenprocess
Aencountersaproblemandiskilledandremovedtromtheprocess tree,
process B, vhich is still running, is said to have been
orphaned.MemoryManagement
Memorymanagementsottvareallovsyoutomanageallotmemoryincludingbothphysical
memoryandvirtualmemory. Virtual nenory istheconceptot
thesystemutilizingphysicalmemoryasvellasasectionotharddiskspacetoraccommodatingmultiple
processes. 1he use ot virtual memory tacilitates the multiuser and
multitaskingteatures and capabilities ot an operating system.1he
area on Lhe hard disk reserved or virLual memory is someLimes
called Lhepae ile or swap ile. 1heswap ile is creaLed durin Lhe
insLallaLion o LheoperaLin sysLem.Hereishovvirtualmemoryvorks.
Programsareloadedintophysicalmemory, alsoknovn as randon access
nenory (RAM). Programs are allocated a certain amountot time,
called a time slice.When memory utilization reaches a certain
threshold or vhena process`s time is up, the system sends the
program and its data to the hard drive.
Heretheprogramisinavaitstateandisplacedtemporarilyonhold.
Whenthesystemisreadytoprocesstheprogramanddatathatiscurrentlyonhold,
theprogram`sdataissent back to physical memory tor main
processing.Maintrameoperatingsystemsandsomenetvorkoperatingsystems,
suchasNovellNetWare, LNIX, Iinux, and Windovsplattorms,
utilizevirtualmemory. Onevaytospeed up your computer system is to
add more memory to it. Another vay is to increasethe size ot your
svap tile by allocating more disk space to
it.8MT1ProgrammIngLanguagesSottvareprogramsarevritteninlanguagessuchasC,
C, ava, VisualBASIC,COBOI, lOP1PAN or Assembly. Ianguages are
divided into tvo major classiticationsHigh-levelIov-level
HIgh-level ProgrammIng Languages High-level programming languages
are designedvith people in mind. 1hey tend to be similar to Lnglish
in style and are much easier
tortheprogrammertoreadandcomprehendthanlov-levelprogramminglanguages.
lorexample, reviev the tolloving excerpt ot a COBOI programming
language statementIF HOURS > 40 THEN PERFORM
CALCULATE~OVER~TIMEELSE PERFORM
CALCULATE~REGULAR~TIMEEND~IFIntheexample, itthehoursexceed40,
thenovertimeiscalculated. Itthehoursareunder and including 40,
thenregulartimeis calculated. You can clearly seehovthissample
COBOI program is very much like Lnglish. Lxamples ot high-level
program-minglanguagesinclude Perl, COBOI, C, BASIC, VisualBASIC,
andlOP1PAN.High-levelprogramminglanguagesmustbeconvertedtromtheirhuman-readabletorm
into computer- or machine-readable torm.1his conversion can be done
througheither 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 itis tree ot errors and compiled, the
program is capable ot being run or executed. On manysystems,
itisjustamatterotclickinganiconrepresentingtheprogram.
Lxamplesotcompiled languages are C, C, COBOI, and lOP1PAN.In the
case ot interpreting, each line is converted into machine-readable
torm as it isexecuted. 1he statements vithin the program are still
converted into machine-readabletorm, it`s just done line by line.
1hink ot an interpretive language as being one vhere
aminicompileisdonetoreachstatement.
SomeexamplesotinterpretivelanguagesareVisual BASIC (hovever you can
compile the code,, Perl, BASIC, and shell
programs.Low-levelProgrammIngLanguages
Lachprocessorhasitsovnprogramminglanguage,
ottencalledalov-levelprogramminglanguage. 1heterm lov-level
isusedbecausethelanguageisnativetotheprocessorinsteadotbeingsimilartoLnglish.
Lxamples ot these are the Assembly language statementsthat are
specitic toeverycomputersystem. So, youcouldnottakean
Assemblylanguageprogramand12 Chapter 1IntroductIon to the OperatIng
System nvIronmentUnderstandIng ClassIfIcatIons of Software 13run it
on just any system. Hovever, you are more likely to take a
high-level
programandrunitonanothersystemvithmaybeonlyatevmoditications.
1akealookatthe tolloving excerpt trom an Assembly language programL
l,XA l,YA l,ZST l,T1he above programming codesimply adds up a set
otthree variables, X,Y, and Z, andstores them in avariable named 1.
It is not like Lnglish, and it greatly ditters trom theCOBOI
program example you sav earlier.DevIceDrIversKeep in mind that it
you have a piece ot hardvare, such as a printer or scanner, you
musthavesottvarethatgovernsit. Device drivers
aresottvareinstructionsthatmanageaparticulardevice.
Youmustcontigurethecorrectdrivertorthetypeothardvareyouinstall.
Lntortunately, it`snotuncommontoinstalladevicedriverincorrectly.
1akeaprinter driver tor example. A possible symptom ot an
incorrectly installed printer
driveristhattheprinter`soutputisgarbledandunreadable.
Anothersymptomistheprinterprints 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 oLherwords, 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.SoftwareUtIlItIesSoftvare utilities are commands that help
augment the tunctionality ot the operatingsystem.
1heyareespeciallyimportantbecausetheycanbeusedincombinationvithshell
script programming logic to automate certain tasks.1he tolloving
are some sottvare utilitiesBackup and restore Compression and
uncompression Printer managementackup and Restore One ot the most
important aspects ot any job is backing up yourdata.Whether you
back it up to a tloppy disk, CD, hard drive, or tape, you should
alvaysback up your data. Although many organizations use redundant
servers in case one goesdovn, or they use redundant disks storage,
they still require their personnel to pertormbackups.8MT1Backups
typically occur during ott-hours vhen users are not vorking vith
applicationtiles. 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 momentby 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 originalstoragelocationoranotherone. 1he
backup andrestoreprocessesshouldbetestedtoverity they vork in case
a real emergency ever occurs.CompressIonandUncompressIon
Mosteverytilehassomethinginitthatisrepeated. lor example, one ot
the most common vords is the vord the, vhich occursin many
documents and books, such as this one. Conpression is the process
ot remov-ingthose repeatingportionsotatile, therebymakinganev
smallertile. Compressionvaries based on the amount ot data that is
duplicated and the compression algorithm thatis used.At times,
compression can yield betveen a 73 and 90 savings.You vould
gen-erallycompressatilethatistobedovnloadedovertheInternet.
Ittakeslesstimetodovnloada compressedtilebecauseitissmaller.
Anotheradvantage otcompressionisthat it saves disk space because ot
the reduced tile size. Hovever, in order to utilize thetile, you
must uncompress it tirst.PrInter Management 1he Iinux printing
system uses the concept ot print queues totemporarily hold print
jobs. When a user sends a print job to a printer, the print job
isspooled 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 othersystem activities. It the printer is busy or
not turned on, the printjobvaits in the print queue until the
printer is ready to accept the request.When the
printerisreadytoprint,
theprintmanagementsottvarelooksintheprinter`sdirectory, orqueue,
and prints the next job. It then deletes the print job request trom
the print queue.ApplIcatIon SoftwareApplicationsoftvare
issottvarethatassistsusersinpertormingtypicalotticevorksuch as
vriting letters and business proposals, managing numeric
intormation, and orga-nizing large amounts ot data. As such,
application sottvare is generally divided into thesemajor
categoriesWord processingSpreadsheetDatabase8MT14 Chapter
1IntroductIon to the OperatIng System nvIronmentUnderstandIng
ClassIfIcatIons of Software
15Word-ProcessIngSoftwareWord-processingsottvarehasbeenaroundsincetheearly1980s.
Word-processingsott-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, anda thesaurus.1oday, Microsott makes Word and Sun
Microsystems otters a vord-processingpackageaspartottheStar
Otticesottvarepackagesuite. Star Otticeruns ontheIinuxoperating
system.SpreadsheetSoftwareAlso during the early 1980s, a group ot
studentstaking an accounting class grev tiredot making numerous
changes to the accounting sheets vhen only one number changed.1hese
students eventually started the Iotus Corporation, one ot the tirst
companies tocreate spreadsheet sottvare tor PCs. Spreadsheet
programs allov you to manage numericdata 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
arelabeledconsecutivelystartingvithA1andcontinuingastarasyourdatademands.Ietters
represent the columns and numbers represent the rovs.Spreadsheet
programs are extremely povertul and can include programming
logic.1heyalso include built-in tunctions. Functions are
miniprograms that do the vork vhen yousupply 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
spreadsheettunction.1he AVERAGE tunction is given, or passed, tvo
valuesthe beginning cell in a cellrange,A1, and the ending cell in
a cell range, A20.Whatever values are held in any ot the 20cells in
column A are included in the average. It a value in any cell in the
range changes, theaverage changes too.DatabaseSoftwareDatabase
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.Dataheld in databases
can beaccessed quickly viaa unique identitier calleda key
tield.Ashton-1ate Corporation developed one ot the tirst database
programs on the market torPCs in the 1980s called dBASL. Other
companies such as IBM, Microsott, Oracle, and SunMicrosystems have
also developeddatabase sottvare. Iinux comes vith a database
prod-uct called MySQI. It allovs you to add, delete, and modity
data vithin databases.8MT19NDRS1ANDING(A1AIn order to successtully
vrite shell script programs, you must understand vhat data is
asvell as the structure ot data. Data is made up ot rav tacts that
are not much use untiltheyare processedintointormation. Considerthe
number 73. 1his isconsidered data.You cannot look at the number 73
and tell it it is an exam grade, the outdoor temper-ature,
orsomeone`sage. Onlyvhenaprogram,
inconjunctionviththecomputer`sprocessor, processes the number can
it become intormation. 1he programmer`s job is tovrite programcode
toturn datainto usetulintormation. 1hinkotdata asahierarchyor 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
andis either a zero (0, or a one (1,. Lach computer system has a
character set that maps allthe letters on the keyboard to its
appropriate bit sequence. American Standard Code
torIntormationInterchange(ASCII,isacharactersetcommonamongmostcomputerenvironments
including all Windovs operating systems and the Iinux operating
system.Although you don`ttypically use anything as smallas abit in
your daily dealingsvithcomputers, you do need to understand the
concept.In the computer industry, the term byte reters to eight
bits taken in sequence.
Anothersynonymtorthetermbyteisalphanumericcharacter.
Analphanumericcharacterisdetinedasanyottheletters AthroughZ,
numbers0through9,
andspecialsymbols.Althoughitisuponenotchonthedatahierarchy,
acharacterisgenerallythelovestlevel ot the data hierarchy that
people process.Records:1asha Liu, 400 Yona Dr., 8eijin, ChinaFred
SmiLh, 201 Apple Lane, ALlanLa, GA, 30033Fields: 1asha Liu,
Lires8yLes: A 8 7 9 ; > z8iLs: 0 0 1 1 0 0 1
0Files:Payroll.daLlnvenLory.daLfIgure 1-7 DaLa pyramid16 Chapter
1IntroductIon to the OperatIng System nvIronmentUnderstandIng Data
17A group ot bytesis called a field. lor example, it you`ve ever
tilledout a job or collegeadmission application, or even your 1040
tax torms, you knov that you must till in littleboxes or blank
lines vith your personal data. Lach ot the boxes or blank lines is
enteredinto an application screen to be processed by a program.
1hese boxes and blank lines areconsidered 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 data1ashaIui. It you vanted to print the NAML tield,
it vould print the name 1asha Iui. Noticealso that a tield is
comprised ot characters or bytes.A group ot related tields makes up
a record. lor example, consider the employee recordscontaining the
tield names and data shovn in 1able 1-3. 1here are three records
vith sixtields 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 theprinary
key field. 1his tield is used to access the remaining tields in the
records. 1hepurpose ot the primary key is to locate the data in the
record etticiently. When a banktellerasks you toryourbank
accountnumber, theaccount number is usedas the pri-mary key.Your
Social Security number is used as a primary key vhen you till out
yourtax returns or an employment application.1o help you understand
the primary key concept, think about hov the index in the backot
this book vorks. It you vant to look up a term, you go to the index
and look throughthe 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
analogoustothetermyouseekintheindex. Inanapplication,
theprimarykeytieldisusedtolocate 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 vherethe 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
havebeen compiled and pertormsome typeotoperationortask.
1heyarevrittenusingtexteditorstollovingthestrictsyntaxotthe
language and then they are compiled.1he compilation process creates
the executablecode. 1he commands that you`ll use in this book are
executable tiles.Name Address CIty State ZIp PhoneSarah 1oar 214
ScoLL Way Concord NH 03301 555-5550Xin Chun Liu 428 Aubrey Way
Lilburn GA 30047 555-5551Nolly Obakin 1027 Nichelle Lane 1ulsa OK
74101 555-55571able 1-3 Sample employee records1Noneecutable files
are generally data that the executable tiles operate on.1he user
runsan application or program that creates data tiles. Data tiles
can also be created automaticallyby programs that run vithout user
intervention. Lxamples ot nonexecutable tiles are texttiles,
vord-processing document tiles, spreadsheet tiles, database tiles,
or picture tiles.9NDRS1ANDING9SR6OLSIntheIinuxcomputing
environment, thereareseveraltypesotusers, eachvithdit-tering roles.
Lnderstanding the role ot a user is important because it helps you
decidethe 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 typesStandard
userSystem Administrator or root userShell programmerStandard 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 modeandotherprogramsintheGLI.
1heyalsousethesystemtoaccessapplications. 1heapplications
theyneeddependupontheir tunctions intheorganization.
Considerthisexample ot typical users` needs. An accounting manager
may need access to the account-ingapplication,
anengineermayneedaccesstoacomputeraideddesigncomputeraided
manutacturing (CADCAM, program, an insurance agent may need access
to theinsurance 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
computerspecialist, such as a System Administrator vho has
authority to create the accounts, gen-erates the useraccounts. 1he
user account should also havea passvord that is assignedto 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 operationsot the computer systems and
netvork. Depending upon the size ot the operation, there maybe 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 usersduring the
hours needed by the users.System Administrators pertorm a variety
ot tasks including upgrading applications
andinstallingsystemsottvare, changinguserpassvords,
monitoringthenetvorktorbot-tlenecks, and in some cases, changing
printer toner cartridges. Some have to be on call24 hours a day to
provide support tor multiple shitt operations.18 Chapter
1IntroductIon to the OperatIng System nvIronmentUnderstandIng User
Roles 19System Administrators also maintain security, making sure
users have the right access toapplication tiles and tolders on the
computer system. 1he goal is to give each user justvhat 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
hastheabilitytopertormsystemadministrativevork,
suchasaddaprintqueue, changeanother user`spassvord, or backupa
system tile, standarduser accountsdon`thave theability to do these
things. In Iinux, the name ot the user vith complete
administrativecapability is called root.1he root user has access to
programs and contiguration tiles thatstandard users don`t.You musL
use cauLion when loin in as Lhe rooL user because you can
deleLeormodiyconiuraLionilesandproramsLhaLareunrecoverablewiLhouLcompleLely
reinsLallin Lhe operaLin sysLem.Dependingupontheorganization,
theSystemAdministratormayberesponsibletorvriting 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 thatis vritten to automate a
process in the Iinux operating system. A shell programmer vritesthe
script using an editor, tests the script, and vhen the script
passes the tests, makes the scriptavailable to users.1he shell
programmer must have an understanding ot programming con-cepts as
vell as the Iinux commands in order to successtullyvrite scripts.
lor example, ashell programmer may need to vrite a script that uses
system commands and decision logictor a System Administrator vho
needs a vay to automate the backup process. Or a shell
pro-grammermayneedtocreateamenusoseveraluserscanrunIinuxcommandsvithoutentering
the complete syntax ot the command.1ypically, a shell programmer
logs in using aregular 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 logicerror trom scripts or
programs.A synta error is one that does not contorm to the rulesot
the language. An example ot asyntax error is a misspelled command.
A compiler orinterpreter usually displays an error message vhen it
encounters a syntax error. A scriptor programcan not run untilit is
syntax-error tree. Shell programmers must learn thesyntax 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 logicerror
isanerrorthatdoesnotmeettherequirementsottheprogramminglogic as
decided upon by the users and management. 1hese are typically more
ditticulttortheshellprogrammertoidentitybecausethescriptsaremostlikelysyntactically8MT1correct.1he
compiler or interpreter does not display a message indicating the
error andtheprogramappearstorunnormally.
Anexampleotalogicerrorvouldbeusingaless-than symbol instead ot a
greater-than symbol in an overtime calculation script. Inthe
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 morethan 40 hours vill have their pay
calculated on regular time. 1he program vould runbecausetheuseot
theless-thansymbolissyntacticallycorrect,
buttheoutputotthecodevouldbeundesirable.
ComparethisexampletotheearlierCOBOIexamplevhere use ot the
greater-than symbol (> 40, is logically correct.IF HOURS < 40
THEN PERFORM CALCULATE~OVER~TIMEELSE PERFORM
CALCULATE~REGULAR~TIMEEND~IF9NDRS1ANDING&ASIC0INUX'OMMANDS1he
Iinux operating system contains numerous commands. Some are only
available toSystem Administrators and not to standard users, vhile
other commands are available toeveryone.You need to learn about the
commands that are available to all users becausethey may also be
used in shell scripts.LoggIng In and LoggIng OutOne ot the tirst
things you need to knov is hov to log in to the Iinux system.You
needa username and passvord. (1o complete the activities and
projects in this book, you mayneed 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 trontot the system and
enter you username and passvord. Second, you can use the
telnetcommand to log in to the Iinux system. 1his requires the host
to have an IP address orDNS 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 commandto connect to it it it is.You vill access the Iinux
system trom a Windovs-based system thatis 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 1IntroductIon to the OperatIng System
nvIronmentUnderstandIng asIc LInux Commands 214. 1ype ping
hostnameZhostaddress, and then press Lnter. Be sure tosubstitute
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 isinaccessible. See your instructor. Do not go to
the next step.6. 1ype telnet hostnameZhostaddress, and then press
Lnter. Be sure tosubstitute your correct host`s name or IP address.
1he Iinux login promptappears. ligure 1-8 includes the logging-in
process to the Iinux system tromthe Windovs command prompt.7. 1ype
your usernane, and then press Lnter.Your username appears on
thescreen, and you are prompted tor a passvord.8. 1ype your
passvord, and then press Lnter.Your passvord vill not appear onthe
screen tor security reasons.You have nov successtully logged in and
haveaccess to the Iinux system.9. 1o log out, type logout, and then
press Lnter.Your connection to theIinux 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.1heGEP CommandOnce 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 usethe cal command to display a variety ot months
and years. Here is the general tormatot the commandcal month
yearfIgure 1-8 Loin in Lo a Linux sysLem rom a Windows-based
PC8MT11he 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.1heyear 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 theyearonly. lorexample, the
tollovingstatement displaysthecalendar torthetirstninemonths tor
the year 2004.cal 2004ligure 1-9 shovs the partial calendar tor the
year 2004.1heGEX Command1he cat command allovs you to display the
contents ot text tiles very easily. You
sim-plytypeinthecommandtollovedbythetilename,
thetextdisplaysonyourscreen.Atter the command completes its task,
your prompt returns.1he cat command is derived trom the term
concatenate vhich means to join or tusetogether. 1he cat command
concatenates the contents ot a tile on your disk vith thescreen.
1he command takes the tolloving tormcat ot1on f11enameHere is an
example that displays the contents ot the sales tilecat salesfIgure
1-9 1he resulLs o Lhe cal2004 command22 Chapter 1IntroductIon to
the OperatIng System nvIronmentUnderstandIng asIc LInux Commands
231he cat commandnotonlyallovsyoutodisplaytextonthescreen,
butalsoallovsyou to create a tile. 1o do this you use the
greater-than redirection operator, >. At thispoint, all you need
to understand is that the output ot the cat command is redirectedto
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 thendisplay 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. 1he1erminal emulation program vindov
appears vith your prompt.3. 1ype cat > file2.txt, and then press
Lnter. Notice that the cursor movesto 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 atthe
completion ot each lineShell Programming will help me on the
job.Linux is fun!WhencreaLinailewiLhLhe cat
command,onceyou'vepressedLnLer aLLhe end o a line, you cannoL o
back Lo LhaL line and ediL iL. CreaLin a ileusin Lhe cat command is
or quick Lasks. 1o ediL Lhe ile, you need Lo use oneo 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 pressLnter. ligure 1-10
shovs the contents ot the tile you just created as vell asyour
creation ot that tile.7. 1o exit the vindov, type exit, and then
press Lnter.8. Iog out.2SXI8MT11heHEXI Command1he date command
displays or sets the system date and time. Here is the general
syn-tax ot the commanddate ot1on +format1able 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 Lhedate +%DLwo-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 Limedate +%T% Displays Lhe numeric day rom 001 Lo 366;
Lhis is someLimes calleddate +%Lhe Julian daLe%m Displays Lhe
Lwo-diiL monLh date +%m1able 1-4 OpLions or Lhe date commandfIgure
1-10 1he cat command Lo creaLe a ile24 Chapter 1IntroductIon to the
OperatIng System nvIronmentUnderstandIng asIc LInux Commands
25ligure 1-11 shovs a screenshot ot the date command run using
various tormats shovnin 1able 1-4.1heIGLS CommandYou use the echo
command to display text on the screen. As such, the echo commandis
a very usetul debugging tool that can help you troubleshoot shell
script programs.1heecho command takes the torm ot the tollovingecho
"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 learnmore
about use ot quotes in Chapter 3. Consider this exampleecho "How
are you doing?"You can use the echo command to create a tile.
Hovever, using the echo command todo this is only recommended vhen
you only need a small tileconsisting otjust a tevlines.
1odothisyouusethegreater-thanoperator, >,
toredirecttheoutputtromthescreen 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 salesecho "March sales
exceed proections for the Houston Branchoffice." > salesNext you
vill use the echo command to redirect text to the sales tile, and
then use thecat command to display the contents ot the tile.fIgure
1-11 1he date command run wiLh dierenL ormaLs11o 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. 1he1erminal emulation program vindov appears vith your
prompt.3. 1o redirect the output to a tile named sales, type the
tolloving code, andthen press Lnterecho "March sales exceed
projections for the Houston Branchoffice." > sales1he command
executes but returns no output to the screen because theoutput 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 theecho command
and it`s displayed using the cat command.3. 1o exit the vindov,
type exit.6. Iog out.1heLMWXSV]
CommandItyouvanttoseethecommandsyou`vealreadyentered,
youcanrunthehistorycommand.1his command is usetul tor saving
keystrokes.You can use your up and
dovnarrovstogoupanddovnthroughyourhistorylisttolocateacommandyouprevi-ously
entered. Once you locate the command you can use the backspace key
to modityit, or you can press Lnter to rerun the command as
is.fIgure 1-12 1he echo command used Lo creaLe Lhe sales ile26
Chapter 1IntroductIon to the OperatIng System
nvIronmentUnderstandIng asIc LInux Commands 27Here is the general
tormat ot the command historyhistory
ot1onItyouenterthehistorycommandvithoutanyoptions,
itdisplaysthelast1,000commandsyou`veentered. Lsedvithoutanyoptions,
itcanprovideyouvithmoreintormation than you may be prepared to deal
vith. Here are a tev vays you can usethe history command.1he
history command teature allovs you to enter a recently executed
command byplacing the ! operator prior to the command. So, to rerun
the most recently executedcal command, enter!calYou don'L have Lo
enLer Lhe compleLe command when usin Lhe ! operaLor.For example, i
you enLered, !da, Lhe mosL recenLly execuLed command LhaLbeins wiLh
Lhe leLLers "da" is execuLed. l Lhe date command was Lhe
mosLrecenLly execuLed command, Lhen iL would be rerun.1he history
command displays numbers to the lett ot each command in its list.
It you seea command in the history list that you vant to rerun, you
can enter the ! operator tollovedby the number ot the command in
the list. So, to rerun the 1031WXcommand in the list,
enter!l03lligure 1-13 shovs a screenshot ot running the history
command using the ! operator.fIgure 1-13 1he history command usin
Lhe ! operaLor8MT11hePTV Command1he lpr command places a tile in
the print queue tor printing.You use this commandto send a document
to the printer.1he tormat ot the command lpr islpr ot1on f11ename1o
print the sales tile you created in an earlier exercise, you enter
the tolloving codelpr salesAlthough 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 printthe sales tile to a printer named IinuxPrinter,
enter lpr ~P LinuxPrinter sales.NosL commands allow you Lo enLer
opLions. However, because each commandhas a dierenL uncLion, Lhe
ormaLs o Lheir opLions are usually dierenL. For LhemosL parL, an
opLion is preceded by eiLher one or Lwo dashes, as in ~t.1heQER
Command1he man command allovs you to display the manual, or help,
pages tor a command.Yourun this command to see a description ot a
command and its options, it it has any. 1hegeneral torm isman
command1ousetheman commandtodisplaythemanualpagestortheecho
command, enterman echo. ligure 1-14 shovs a screenshot ot the man
pages tor the echo command.fIgure 1-14 1he manecho commandDeLails
Lhe opLions used byLhe commandSummarizes Lhe commandand any opLions
ordaLa neededName o Lhe commandollowed by a shorLdescripLion8MT28
Chapter 1IntroductIon to the OperatIng System
nvIronmentUnderstandIng asIc LInux Commands 291heXSYGL Command1he
main purpose ot the touch command is to update the moditication
date and timestamp 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 thetouch command tor the tile. 1he
touch command takes the tolloving tormtouch f11enameYou can also
use the touch command to create an empty tile and set the
moditicationdate and time on that tile using the same torm.1he[LS
Command1he who command allovs you to display the list ot users vho
are currently logged onto the Iinux system. 1he torm ot the command
is as tollovswho ot1onsYou 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 commands1Peter to 1able 1-3 tor a listing ot the
common basic Iinux commands.'RA1ING7HLL7CRIP1SBecause 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 traditionalprogramming concepts the shell allovs you to
pertorm vith scriptsMake decisions based upon conditionsPertorm
arithmetic operationsCreate a menu using looping statementsLse
tunctions to pertorm very specitic tasksManipulate data using an
array1he Lerms "scripL" and "proram" are synonymous.A shell script
pertorms one other tunction that traditional programming languages
do nottypically support, the shell script runs operating system
commands. Iike other programminglanguages, you vrite your shell
script, and then you execute it. Next you vill create a sim-ple
shell script.8MTCommand DescrIptIoncal Displays a calendarcat
Displays Lhe conLenLs o a ileclear Clears Lhe screendate Displays
or seLs Lhe daLe and Limeecho Displays LexLhistory Displays
previously enLered commandslogin and logout Allows you Lo lo in and
lo ouLlpr PrinLs a ileman Displays manual (help) paes or a
commandping DeLermines i anoLher 1CP/lP sysLem is availabletelnet
ConnecLs Lo a 1CP/lP compuLertouch UpdaLes Lhe modiicaLion daLe and
Lime o a ilewho Displays Lhe currenLly loed on users1able 1-5 8asic
Linux commands30 Chapter 1IntroductIon to the OperatIng System
nvIronmentCreatIng Shell ScrIpts 311o 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.
1he1erminal 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 script1echo
"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.Yourscreen should look like ligure 1-16 vhich
shovs the script you have input asvell as the resulting output.7.
1o exit the 1erminal emulation program, type exit, and then press
Lnter.8. Iog
out.1oreintorcevhatyou`vealreadylearnedaboutusingcommandsandcreatingshellscripts,
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
ouLpuL11o create a shell script vhich displays the calendar, the
current tine, and theusernanes 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. 1he1erminal
emulation program vindov appears vith your prompt.3. 1ype cat >
script2, and then press Lnter to create a nev tile namedscript2.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
loggedin. Press Crl+D to terminate the line. 1he prompt returns.7.
1o execute the script, type bash script2, and then press
Lnter.Yourscreen should look like ligure 1-17 vhich displays the
script you have inputas 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
ouLpuL32 Chapter 1IntroductIon to the OperatIng System
nvIronmentChapter Summary 33'HAP1R7UMMARY1he operating system is
the sottvare brains that manage the computer system.1he operating
system interacts vith users, the applications, and the hardvare.
Allcomputer systems must have an operating system in order tor the
system to run.1he Iinux operating system is a portable, multiuser,
multitasking, and multiprocessingsystem. 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.
Systemsottvare 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 printermanagement
sottvare. 1he kernel is the nucleus ot the operating system. It
remainsin memory and controls other sottvare components.Data is
made up ot rav tacts. Intormation is processed data. A bit is
either a binaryzero or one. A byte is a group ot eight bits. A
tield is a group ot bytes. A record is agroup ot tields. A primary
key tield is a special tield that allovs you to quicklyaccess a
record in a tile. A tile is a group ot records. 1here are tvo types
ot tilesexecutable, 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 aperson vho uses the application and system on a
daily basis to pertorm a certainjob tunction such as payroll,
accounting, marketing, tinance, or engineering. ASystem
Administrator is responsible tor maintaining, monitoring,
upgrading, andtroubleshooting the system and netvork so users can
do their jobs. A shell pro-grammer vrites shell programs tor users.
Shell programmers apply their knovledgeot 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 insome vay.You use the manual pages tor the
command you vant to learn more about.Shell script programming
combines programming logic structures vith operatingsystem commands
to automate routine tasks. 1he shell runs commands in the
shellprogram.16VIW5US1IONS1. is the sottvare that remains in memory
and controls otheractivity.a. Kernel b. Sottvare utilitiesc. Backup
sottvared. ob management sottvare2. Shell script programs usually
run in themode ot Iinux.a. X Windovsb. MS Windovsc. graphicald.
text 3. Which ot the tolloving is an interpreted languagea. COBOIb.
Cc. Cd. Bourne-Again Shell (bash,4. A spreadsheet is an example
otsottvare.a. backupb. application c. print management d. assembly
language3. A group ot tields is also knovn as a.a. byteb.
characterc. record d. table6. Hov many bits are in a bytea. 1b. 2c.
4d. 8 34 Chapter 1IntroductIon to the OperatIng System
nvIronmentRevIew QuestIons 357. What company tirst developed LNIXa.
Microsottb. Iinuxc. Ped Hatd. A181 8. is another name tor a
process.a. ob b. Disk drivec. lolderd. X Windovs9. Which command
allovs you to display the manual pages tor a commanda. manb.
pagesc. whod. lpr10. When vas LNIX developeda. 1960sb. 1970sc.
1980sd. 1990s11. Which command allovs you to display the tvo-digit
daya. date +%Yb. date +%Tc. date +%dd. date +%D12. is rav tactsa.
Intormationb. obc. Data d. Daemon113. is a background job.a.
Intormationb. obc. Datad. Daemon 14. 1hecommand sends a document to
the printer.a. lprb. printitc. dated. echo "Hi" > file4.txt13.
Ais a group ot related records.a. tieldb. tilec. bitd. character16.
Ais a person vho uses the system on a daily basis to do hisspecitic
job, such as manutacturing, accounting, or payroll.a. System
Administratorb. standard userc. shell programmerd. daemon 17. Ais a
person responsible tor making sure the systems and net-vorks are
available to the users vhen needed.a. System Administratorb.
standard userc. shell programmerd. job18. A picture tile is an
example ot atile.a. binaryb. executablec. nonexecutabled. job
management36 Chapter 1IntroductIon to the OperatIng System
nvIronmentHands-on Projects 3719. A command is an example ot
atile.a. binaryb. nonexecutablec. print queued. X Windovs20. Ais a
person vho vrites scripts as his or her main job tunction.a. System
Administratorb. standard userc. shell programmerd. print
queue,ANDSON4ROJC1SProject 1-1Inthis project, you vill visit an
organizationthat uses the Iinux operating system
anddiscussthetypeothardvareandsottvareituses.
You`llalsorecordittheorganizationuses any scripts, and it so, tor
vhat purpose.1. Iocate an organization that uses the Iinux
operating system as the main operatingsystem tor their
organization.2. Pecord the name ot the organization.3. Interviev
one ot the System Administrators or other persons responsible tor
thecomputer 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-2In 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,
andproduct otterings ot the Ped Hat version ot
Iinux.,ERHWSR4VSNIGX,ERHWSR4VSNIGX14. 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, andproduct 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,
andproduct otterings ot the Iinux version ottered by
Mandrake.Project 1-3In this project, you vill execute basic Iinux
commands to help you understand hov tointeract 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 otrecently 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-4In 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.,ERHWSR4VSNIGX,ERHWSR4VSNIGX38 Chapter 1IntroductIon to the
OperatIng System nvIronmentHands-on Projects 397. 1ype cal month
year vhere month is your tvo-digit birth month and ear isyour
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-5In 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 scriptecho "Welcome to my shell script."echo "This is
one of my first shell scripts."echo "Shell script programming is a
tool for helping SystemAdministrators."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 haveaccess 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-6Inthisproject,
youvillvriteashellscripttodisplaythecurrentuliandateandthenumber 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 mayhave to get the
printer name trom your instructor.,ERHWSR4VSNIGX,ERHWSR4VSNIGX110.
Close your 1erminal emulation vindov.11. Iog out.Project 1-7In 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
torthat option.4. 1o use the option, type cat ~option Project1-6
vhere option is the letteryou 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 hasnot 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, andthen record the option and
its description.9. Pun the command using the option you chose, and
then record the commandand the option you chose.10. Close your
1erminal emulation vindov.11. Iog out.Project 1-8Inthis project,
you vill createa scriptcontaining threestatements. Youvill 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 usethe redirection symbol.,3. Lsing
the correct option trom 1able 1-4, insert the date command so it
displaysthe date in MMDDYY tormat.4. Lsing the correct option trom
1able 1-4, insert the date command so it onlydisplays 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.,ERHWSR4VSNIGX,ERHWSR4VSNIGX40 Chapter
1IntroductIon to the OperatIng System nvIronmentCase Projects 419.
Print your script. It you do not have access to a printer, record
vhat displays onyour 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.'AS4ROJC1SCase 1-11MI Corporation is
currently running maintrame computers in a distributed
environment.1hereareabout23usersconnectingviadumbterminalstothemainottice,
locatedinIavrenceville, Georgia.1hey use manutacturing, inventory,
and personnel applications vrit-ten in COBOI. 1heir programmers are
villing to learn other languages but have not
yethadthechancebecausethey`vebeentoobusymaintainingthecurrentapplications.
1hecompany has outgrovn its computing resources. It is in the
process ot selecting an entirelynev computer systemtrom hardvare to
sottvare.Writeaproposaltothecompany`schietintormationotticer(CIO,convincinghertochoosetheIinuxoperatingsystem.
Includespeciticationstorthe 1MICorporation,accounting torenough
computers to service the current number otusers, tvo
servers,andtiveprinters.
Indicatetheprogramminglanguagethenevapplicationsshouldbevritteninandsupportyourdecision.
IncludearationaletorsendingtvoSystemAdministrators to attend Iinux
administration classes.Case 1-2 1heDaisyMae
WooHaberdasheryCorporationcurrentlyisrunningaproprietaryLNIX
operating system trom the XYZ Corporation vendor. 1he XYZ
Corporation isgoingoutotbusinessbecauseotadovnturnintheeconomy.
1heDaisyMae WooHaberdashery`s business is thriving, but they are
vorried about the potential lack ot sup-portinthetuture.
1heDaisyMae WooHaberdasheryhastiveremoteotticeslocatedvithin 10
miles ot its main ottice.1he Daisy Mae Woo Haberdashery has
tinancial appli-cationsrunninginCandmanyottheSystem
Administrationtoolsare vrittenintheBourne 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 vithversions ot MINIX.1he Daisy Mae Woo Haberdashery
Corporation has decided to go vith a nev vendor,theAlphalirm,
torconsultingservices. Writeaproposalto 1heDaisyMae
WooHaberdasheryCorporation asit you vere a vice president tor the
Alphalirm.
IncludeinyourproposalvhichversionotIinuxyouvouldrecommend,
theshellyouvouldsupport, and hov you vould go about migrating the
current programs to the nev sys-tem. Detend your decision on
paper.'EWI4VSNIGXW'EWI4VSNIGXW143',%48)6
92()678%2(-2+8,)0-29. 1hetollovingexamplesorts a tile
namedunsort.datandplaces the outputtoanev tile named sort.dat.1he
original tile remains intact.1here is no output to the
screenbecause it is being redirected to atile. 1he name ot the tile
tolloving the greater-thansymbol is user detined.sort unsort.dat
> sort.datBy detault, the sort command sorts in ascending order,
or lover to higher.You can sortin descending order, called reverse
order, using the ~r option as in this commandsort ~r f11ename1heGYX
Command1he cut command allovs you to strip text out ot tiles and
display the cut text on the screenor redirect the text to another
tile. 1his command is most otten used to cut tields vithin
atile.1he data is not permanently cut trom the tile.1he command
does not alter the originaltile and it automatically opens the tile
tor you.1he basic syntax tor the cut command iscut
ot1onsf11enameYouneed to be avareottvo importantoptions. 1he~d
optionis used toidentitythedelimiterinthetile.
1hecolonisgenerallyusedasaseparatorordeliniter betveentields,
lettingprogramsknovvhereonetieldbeginsandoneends. lorexample,
~d:identities the colon as a delimiter.1he ~f option is used to
identity vhich tield you vantbased on the delimiter. lor example,
consider the tolloving record tor an animal clinicl00l:King
Pup:Dog1he tirst tield,1001, represents the ID, the second
tield,King Pup, represents the ani-mal`s name, and the third tield,
Dog, represents the type ot animal. Colons are used todelimit the
tields in this example.You use a colon, or some other character,
instead ot aspace to separate tields.1he space can not be used
because it may actually separate vordsin a tield, such as King
Pup.Assumingthetileisnamedanimal.dat,
thecommandtodisplaythetirsttieldiscut ~d: ~fl animal.dat.1he
command to display the tirst and third tields vould becut ~d: ~fl,3
animal.dat.2Next you vill create a tile vith several employee
records in it. Lach record vill consistot tvo tieldsan employee
number tolloved by a colon and the employee name.1o use the cut
connand in a file:1. Iog in to the Iinux system as a user, and then
open a 1erminal emulation vindov.2. Create a tile named unsort.dat
using the vi editor.3. Lnter the data in tvo tields. Note in the
data belov, that the tormat isnum|er.name vhere num|er represents
the tirst tield and name represents thesecond tield. 1he colon (,
is the delimiter. Place the tolloving data in the tilenoting that
there are duplicate 3:Jessie records. (You vill use these
tvorecords later vhen you learn about the uniq command., Atter you
enter thedata make sure you press Lnter at the end ot each line,
save the tile, and thenexit the vi editor.3:Jessie James
Garcia3:Jessie James Garcia2:Zachary Scott Pheng4:Lorenzo Todd Von
Schloss1:Micki McSunday-Washington4. 1o cut the tirst tield, type
cut -d: -f1 unsort.dat, and then pressLnter. See ligure 2-13, the
tirst tield appears on your screen, but the data hasnot been
removed trom the original tile.3. 1o cut the second tield, the
names, and then send the output to a tile namedname.dat, type cut
-d: -f2 unsort.dat > name.dat, and then pressLnter. See ligure
2-13.6. 1o display the contents ot the nev tile, type cat name.dat,
and then pressLnter. See ligure 2-13, notice that the nev tile only
has the names in it.7. 1o ensure that the original contents ot
unsortcut.dat have not been literally cut,type cat unsort.dat, and
then press Lnter.1he original contents that verecreated in Step 3
appear unchanged on your screen as shovn in ligure 2-13.8. 1o exit,
type exit, and then press Lnter.9. Iog out.68 Chapter
2UnderstandIng the LInux fIle SystemUnderstandIng fIle Management
Commands 691heTEWXI CommandWhereas the cut command cuts tile
tields, the paste command pastes, or merges, datatrom one tile to
another. 1he data can then be merged into a nev tile.1he basic
syntaxot the paste command ispaste
f11ename_onef11ename_two1heabovecodemergeseachlinetromtiletvovitheachlineottileone.
lorexample,assumeyouhadtvotileseachcontainingnamedata.
1helast.dattilecontentsareSmith Jones Adams, and the tirst.dat tile
contents are Joe Mary Sue. It you enter thecommand paste first.dat
last.dat, then your output to the screen vould beJoe SmithMary
JonesSue AdamsItyouhadenteredthecommandpaste last.dat first.dat,
thenyouroutputvould beSmith JoeJones MaryAdams Sue1he contents ot
the original tiles remain the same.You can also create an
altogether nevtileusingtheredirectoutput(>,symbol.
Ityouenterthecommandpaste first.dat last.dat > first_last.dat,
youvouldcreateanevtilecalled tirst_last.dat vith the pasted data
trom the tirst.dat and last.dat tiles.fIgure 2-13 DemonsLraLin Lhe
cut command1he oriinal ile's conLenLs1he oriinal ile's
conLenLsunchaned1he second ield cuL andplaced in anoLher ile;noLice
Lhe new ile onlyhas names in iL1he irsL ield cuL rom Lheile is noL
acLually removed2Suppose that Mama`s Hardvare Store maintains tvo
separate tiles. One tile is called productand contains the names ot
top selling sale items, and the other tile is called quantity and
con-tains the amount ot the sales items that have been ordered.1he
ovners vould like the intor-mation to appear in one tile named
orders.1o do that, you need to paste these tiles together.ligure
2-14 shovs the contents ot the tvo original tiles as vell as the
use ot the paste com-mand to merge these tiles and redirect the
contents to the nev tile.1heVQ Command1he rm command is used to
remove a tile permanently trom the tile system tree hier-archy.
1here is no vay to recover a removed tile. 1he basic syntax ot the
command isrm f11enameIn the tolloving example, the tile named
resume.dat is removed.rm resume.datSome versions o Linux ask you Lo
veriy LhaL you really wanL Lo remove a
ilebeoreiLisremoved.OLherversionssimplyremoveLheilewiLhouLaskin.Use
cauLion and consider LesLin Lhis concepL by removin a LesL ile
beoreremovin any iles rom your ile hierarchy.fIgure 2-14 1he paste
command or Nama's Hardware SLoreConLenLs o quanLiLy ileConLenLs o
orders ileusin pasteDeaulL display o merinquanLiLy and producL
ilesusin pasteConLenLs o producL ile70 Chapter 2UnderstandIng the
LInux fIle SystemUnderstandIng fIle Management Commands 711heYRMU
Command1he uniq command is to used to tind duplicate lines trom a
sorted tile. 1his is a partic-ularly helptul programming technique
to use it redundant records happen to exist in a tile.1he uniq
commanddoesnotremovetheduplicatelines,
itjustdisplaysthemonthescreen.1he uniq command opens the tile tor
you. 1he basic syntax ot this command isuniq
f11ename1heoutputdetaultstothescreen, displayingtheduplicates.
Youcanalsoredirecttheoutput to a user-detined tilename using the
tolloving commanduniq duplicates.dat > uniq.datIn this case, the
repeating lines trom the duplicates.dat tile are redirected to the
uniq.dattile.You use redirection vhen you vant to reter to the
original data tile. In this case,
youvouldprocesstheuniq.dattilebecauseanyredundantrecordshavealreadybeenremoved
trom the tile.1he uniq command has a usetul option tor counting the
number ot occurrences ot a linein a tile. 1his is helptul vhen you
vant to identity the number ot duplicates you have ina tile.1he
tolloving uniq command vith the attached ~c option accomplishes
thisuniq ~c duplicates.datNextyouvillusetheuniq
commandtoremoveduplicateitemstromagrocerylistvhere several people
in the household have added redundant items.1o use the unig connand
to renove duplicates fron a file:1. Iog in to the Iinux system as a
user, and then open a 1erminal emulation vindov.2. Create a tile
named grocery.dat using the vi editor.3. Lnter the tolloving data.
As you enter the data, make sure you press Lnter atthe end ot each
line. Save the tile, and then exit the vi
editor.soupsouppizzaturkeylettucelettucelettuceapplesbananasgrapesgrapes24.
1o remove the duplicate grocery items, type unig grocery.dat, and
thenpress Lnter. See ligure 2-13.3. 1o redirect this to a tile that
you can take to the grocery store, type unig grocery.dat >
list.dat, and then press Lnter.6. 1o display the contents ot the
nev list, type cat list.dat, and then pressLnter. See ligure 2-13.
Notice that nov the items are part ot the list.dat tile.7. 1o exit,
type exit, and then press Lnter.8. Iog out.fIgure 2-15 OuLpuL o Lhe
uniq commandSLep 6SLep 4 resulLs ouniq command72 Chapter
2UnderstandIng the LInux fIle SystemRevIew QuestIons
73'HAP1R7UMMARY1he Iinux tile system is designed tor storage and
quick access. Directories containother directories or tiles. liles
contain only data. 1he Iinux tile system is hierarchi-cal, or
treelike, in nature. In the Iinux tile system, the root directory
(, is the topot the tree. All tiles and tolders branch trom the
root directory. 1he system directo-ries are created during the
installation ot the Iinux operating system, and theyshould not be
moditied or deleted.When navigating the tree hierarchy, you need to
be avare ot vhere you are, orvhat your current directory is. With
the hierarchy structure, there is a parent-childrelationship. 1he
parent directory is reterred to as dot dot ( .. ,. A child
directoryis reterred to by name. Siblings have the same parent. A
tull path begins at the rootdirectory. A partial path does not
include the root directory.Directory management commands deal vith
manipulating and displaying the direc-tories in the tree. 1he most
commonly used commands are cd tor changing thecurrent directory
location, pwd tor displaying the current directory location, and
lstor displaying the contents ot a directory.Lditors and editor
commands allov you to manipulate the contents in a tile.1he
mostcommonly used editor is vi. It can be used to add, copy,
delete, insert, or modity datavithin a tile.1he tile management
commands allov you to manipulate the actual tiles vithin thetree.
1he cp command is used tor copying an existing tile to another
tile, creatingtvo tiles. 1he mv command is used tor moving or
renaming an existing tile, hov-ever, you end up vith just one tile
vhen you use this command. 1he rm is used toremove a
tile.6VIW5US1IONS1. Lse thecommand to change directory locations.a.
cdb. rmc. mkdird. cut2. Which ot the tolloving are considered tull
paths (Choose all that apply.,a. dirAb. ..dir2c. payrolld. 23. Lse
thecommand to delete a directory.a. delete_dirb. mkdirc. rmdird.
cat4. Which ot the tolloving are considered partial paths (Choose
all that apply.,a. dirAb. ..dir2c. payrolld. 3. Which ot the
tolloving are text editors (Choose all that apply.,a. vib. emacsc.
lsd. cat6. 1hecommand sorts data in descending order.a. sort ~rb.
sortc. mkdird. reverse7. 1o change the vorking directory location
to a sibling directory named dir2, youenter thecommand.a. cd /b. cd
\c. cd ..\dir2d. cd ../dir28. 1hedirectory holds mounted drives.a.
rootb. bootc. mnt d. var74 Chapter 2UnderstandIng the LInux fIle
SystemRevIew QuestIons 759. 1hetile system holds tiles and
directories that vary in size.a. rootb. bootc. mnt d. var10.
1hecommand creates a directory named vinchester in theroot
directory.a. mkdir /winchester b. mkdir ../winchester c. mkdir
\winchester d. md /winchester 11. 1heoption tor the ls command
displays a long listing.a. ~ib. ~ac. ~ld. ~c12. Which ot the
tolloving represents your parent directorya. ..b. .c. d. 13.
1hecommand allovs you to change directory locations to achild
directory named child1.a. mkdir childlb. cd ../childlc. cd childld.
cd /14. In vi, the command to change to insert mode isa. ob. Oc.
id. d213. 1hecommand deletes a tile.a. rmdirb. cdc. rmd. pwd16.
1hecommand displays your present vorking directory.a. catb. cdc.
touchd. pwd17. 1hesystem directory contains the Iinux kernel.a.
bootb. rootc. devd. var18. 1hein the vi editor allovs you to save
and quit the program.a. :wqb. q!c. w!d. !19. 1he command to rename
a tile is.a. mvb. cpc. deld. rename20. 1hecommand makes a duplicate
ot a tile.a. mvb. cpc. deld. rename76 Chapter 2UnderstandIng the
LInux fIle SystemHands-on Projects 77,ANDSON4ROJC1SProject 2-1In
this project, you vill compare your ovn tamily tree to the Iinux
tile system. Pesearchyour tamily tree no turther than your
grandparents. Drav your tamily tree on a separatepiece ot paper,
and then explain hov your tamily tree compares to vhat you`ve
learnedabout the Iinux tile system in this chapter.Project
2-2Inthis project, youvill compare a building`s evacuation plan
toroneroomto the useot paths in the Iinux tile system.You vill
tirst need to get a copy ot a building evacua-tion plan tor one
room trom your local church, school, or vork. 1hen, vrite a
descrip-tion ot hov the evacuation plan relates to a path in the
Iinux tile system hierarchy.Project 2-3In this project, you vill
execute various commands in your home directory.1.Iog in to the
Iinux computer as a user, and then open a 1erminal emulation
vindov.2. 1ype touch file1.dat, and then press Lnter.3. Pepeat Step
2 three additional times, hovever, change the number at the end
otthe tilename each time, e.g., tile2.dat, tile3.dat,
tile4.dat.4.Create a hidden tile by typing touch .hiddenfile.txt,
and then press Lnter.3. Issue a long listing ot all the tiles in
the directory by typing ls -al, and thenpress Lnter.6. On a
separate sheet ot paper, label and identity each column that is
displayed.7. Close your vindov, and then log ott.Project 2-4In this
project, you vill search the Ped Hat Web site tor intormation on
various Iinuxcommands inordertolearnhovto usethe Web
siteasaresearchtool. You vill needaccess to the Internet.1. Open a
Web brovser.2. In the Address or location box on your brovser, type
hiip//uuu.rehai.com, andthen press Lnter. 1he Ped Hat Web site
appears.,ERHWSR4VSNIGX,ERHWSR4VSNIGX,ERHWSR4VSNIGX,ERHWSR4VSNIGX23.
In the Search Ped Hat text box, type ls, and then click the Go
button. 1hescreen displays a listing ot the links to documents
related to the ls command.4. Click one ot the documents and reviev
it. Keep checking documents until youlocate one that gives you
additional insight into the ls command.3. Based on your tindings at
this Web site, identity something nev you`ve learnedabout the ls
command.6. Pepeat Steps 3 through 3 tor the pwd command.7. Pepeat
Steps 3 through 3 tor the cp command.8. Pepeat Steps 3 through 3
tor the vi editor.9. Close your Web brovser.Project 2-5In this
project, you vill execute commands, and then drav the resulting
tree structure.1.Iog in to the Iinux system as a user, and then
open a 1erminal emulation vindov.2. 1ype mkdir Project2-5, and then
press Lnter.3. 1ype cd Project2-5, and then press Lnter.4. 1ype
mkdir R, and then press Lnter.3. 1ype mkdir S, and then press
Lnter.6. 1ype mkdir T, and then press Lnter.7. 1ype cd T, and then
press Lnter.8. 1ype touch t1.dat, and then press Lnter.9. 1ype
touch t2.dat, and then press Lnter.10. 1ype touch t3.dat, and then
press Lnter.11. 1ype cd ../R, and then press Lnter.12. 1ype touch
r1.dat, and then press Lnter.13. 1ype touch r2.dat, and then press
Lnter.14. 1ype cd ../S, and then press Lnter.13. 1ype touch s1.dat,
and then press Lnter.16. 1ype touch s2.dat, and then press
Lnter.17. 1ype cd .., and then press Lnter.18. Drav the resulting
tree structure.19. Close your vindov, and then log
out.,ERHWSR4VSNIGX78 Chapter 2UnderstandIng the LInux fIle
SystemHands-on Projects 79Project 2-6Inthis project, you vill
create adirectory treebased on the output ot the tree com-mand
shovn in ligure 2-16.1.Iog in to the Iinux system as a user, and
then open a 1erminal emulation vindov.2. Create the directory tree
shovn in ligure 2-16.You need to use these commandsto complete this
project cd, pwd, mkdir, and rmdir.3. Pecord the order in vhich you
used each command to create the tree.4. Close your vindov, and then
log out.Project 2-7In this project, you vill create the directory
shovn in ligure 2-17 in order to reintorceyour understanding ot the
Iinux tile system hierarchy.You vill need to use these
com-mandstocompletethisproject cd, pwd, mkdir, andrmdir. linally,
recordthecom-mands in the order in vhich you used them to create
the tree.,ERHWSR4VSNIGXfIgure 2-16 1ree you will creaLe or ProjecL
2-6,ERHWSR4VSNIGX2Project 2-8Inthis project, you vill use the
treestructure trom Project 2-3 to manipulate the tilesand
directories created. Project 2-8 requires completion ot Project
2-3.1.Iog in to the Iinux system as a user, and then open a
1erminal emulation vindov.2. 1ype cd Project2-5, and then press
Lnter.3. 1ype cd T, and then press Lnter.4. 1ype ls, press Lnter,
and then record the output.3. 1ype cp t1.dat t11.dat, and then
press Lnter.6. 1ype cp t2.dat t22.dat, and then press Lnter.7. 1ype
ls, press Lnter, and then record the output.8. 1ype mv t3.dat
t33.dat, and then press Lnter.9. 1ype ls, press Lnter, and then
record the output.10. Pecord the ditterence betveen the cp and mv
commands.11. 1ype cd ../S, and then press Lnter.12. 1ype ls, press
Lnter, and then record the output.13. 1ype cp s1.dat ../R/r5.dat,
press Lnter, and then record vhat this com-mand does.14. 1ype cd
../R, and then press Lnter.13. 1ype ls, press Lnter, and then
record the output.16. Close your vindov, and then log
out.,ERHWSR4VSNIGX$HONLwaLer Lreesoceans seasaLl.daL pac.daL
Red.daLOak.daL Pine.daL8lack.daL.birds.daLfIgure 2-17 1ree you will
creaLe or ProjecL 2-780 Chapter 2UnderstandIng the LInux fIle
SystemHands-on Projects 81Project 2-9In this project, you vill use
vi to create a data tile vith records.You vill then sort the
data.1.Iog in to the Iinux system as a user, and then open a
1erminal emulation vindov.2. 1ype mkdir Project2-9, and then press
Lnter.3. 1ype cd Project2-9, and then press Lnter.4. 1ype vi
infile.dat, and then press Lnter. 1he vi editor opens.3. 1o insert
text, press Lsc, and then type i.6. Lnter the tolloving text and
make sure you press Lnter at the end ot each line.(Lach rov is
considered an employee record vith colons separating the tields.
1hetirst tield is the employee number. 1he second tield is the
employee name, and thethird tield is the employee salary.,401:Sue
Fanglee Tuen:$34000104:Sammy Jones:$55402207:Tammy
Phang:$50040214:Zoe Buhari-Jones:$56000505:James Brongan:$505007.
1o save the tile, press Lsc, and then type the colon symbol (:,.
1he cursor movesto the bottom ot the screen vith a colon to its
lett.8. 1o vrite the tile, type wg!, and then press Lnter. 1he
prompt returns.9. Sort the data in ascending order by typing sort
infile.dat, press Lnter, andthen record the output.10. Sort the
data in descending order by typing sort -r infile.dat, pressLnter,
and then record the output.11.Sort the data in descending order and
redirect the output to another tile by typingsort -r infile.dat
> reverse_sort.dat, and then press Lnter.12. Sort the data in
ascending order, redirect the output to another tile, and
thenrecord the command you used.13. Close your vindov, and then log
out.Project 2-10In this project, you vill use the tiles created in
Project 2-9. Project 2-10 requires com-pletion ot Project 2-9.1.Iog
in to the Iinux system as a user, and then open a 1erminal
emulation vindov.2. 1ype cd Project2-9, and then press Lnter.3. Cut
the tirst tield.4. Cut the second tield.3. Cut the third
tield.,ERHWSR4VSNIGX,ERHWSR4VSNIGX26. Cut both the tirst and third
tield and redirect the output to a nev tile namedsalary.dat.7. Make
a duplicate ot intile.dat by typing cp infile.dat infile2.dat,
andthen press Lnter.8. Open the tile named infile2.dat, and add
tive additional records. Add a sixthrecord that has your name.
Also, create a tictitious employee number andemployee salary to
complete your record.9.1ype diff infile.dat infile2.dat, and then
press Lnter. Pecord the output.10. Close your vindov, and then log
out.'AS4ROJC1SCase 2-1You have been hired by 1MI to design an
application using shell script programs. 1MIneeds you to design and
create a nev directory structure.1he company has several
departments accounting, sales, manutacturing, intormation
tech-nology, andheadquarters.
1heaccountingdepartmenthasaccountsreceivable, accountspayable,
andpayrolltunctionsvithinit. 1hemanutacturingdepartmentruns
threeshittsand a veekend shitt.1he intormation technology
department has tive projects in progress.1he sales department has
ottices located in the West, Last, North, and South.lirst,
designtheIinuxtilesystemhierarchyonpaper.
Keepinmindthatthedepart-ments, tunctions, shitts, regions, and
projects need to translate into directories. Next, youneed to
create this hierarchy on the Iinux system. Create at least one
empty tile in eachdirectory. Lsethedepartment, tunction, shitt,
region, orprojectnameasthetilenameand include an extension ot
.dat.Case 2-2ZonkaCorp. hassalesotticesintivecountries
theLnitedStates, Canada, Spain,Singapore, and lrance. Design your
directory structure on paper and then implement it.Make sure that
each country is represented by a directory. Next, create tvo tiles
in eachdirectory named tirst.dat and last.dat.1hese vill be used to
hold employees` names vithan employee`s tirst and last names split
betveen tvo tiles. In the tile named tirst.dat,
addthetirstnameottiveemployees. Inthetilenamedlast.dat,
addthecorrespondinglastname ot the same tive employees.1hen, using
the paste command, merge the tirst tvotiles together into a nev
tile. lor each employee, the nev tile must have the tirst
nametolloved by the last name on one line. 1hen, merge the tirst
tvo tiles into another tile.lor each employee, this tile must have
the last name tolloved by the tirst name on oneline. linally, make
backup copies ot the nevly merged tiles.'EWI4VSNIGXW'EWI4VSNIGXW82
Chapter 2UnderstandIng the LInux fIle System83',%48)6
7,)00&%7-'7-RXLMWGLETXIV]SY[MPP9RHIVWXERHXLIWLIPPPSKMRERHPSKSYXJMPIW0IEVREFSYXWLIPPZEVMEFPIW&IGSQIJEQMPMEV[MXLXLIWLIPPIRZMVSRQIRX0IEVREFSYXWLIPPFYMPXMRGSQQERHW0IEVREFSYXWLIPPKVEQQEV9RHIVWXERHGSQQERHX]TIW8he
Iinux shell is the program that acts as the intertace betveen you
andthe operating system kernel. 1he shell accepts input in the torm
ot yourcommands, 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 commandprompt. In this chapter, you vill learn hov the
shell is executed and under-stand thepurpose otthe shelland
shellgrammar. Pedirection
villalsobediscussed.9NDRS1ANDING1H7HLL0OGINAND0OGOU1*ILSWhenyoulogin,
ashellisexecutedandprovidesyouvithashellprompt. Youtypeyour
commands to the right ot the prompt. lrom your previous experience,
you
knovthatyouneedausernametologinandinteractviththeoperatingsystem.
Hovever,vhen auser account is created, it is givena detault shell,
vhichis vhat allovsyou toaccess the operating system. lor Ped Hat
Iinux, the detault shell is
bash.AsyouknowromChapLer1,Lhereareseveraldi