Examining the Hamilton C Shell - Scott Richman - Dr. Dobb's Journal - Jan 1991

  • Upload
    msnicki

  • View
    216

  • Download
    0

Embed Size (px)

Citation preview

  • 8/8/2019 Examining the Hamilton C Shell - Scott Richman - Dr. Dobb's Journal - Jan 1991

    1/4

    EXAMIN ING RO O M

    Sarting OS/2 for the first time was,for me, like unlocking a Ferarri,sitting behind its wheel and finding a Yugo's dash. What a disappointment. Sure, the engine andsuspension were first rate, bu t the controls were minimal, the clutch was stiff,and the pedals were nonresponsive!OS/2 comes with great stuff, but CMD.EXE, the default command-line processor, is poor compared to the powerfuloperating system beneath. CMD.EXEappears to be a port of the MS-DOSCOMMAND.COM and lacks the majorfeatures of a serious front end.Fortunately, there's a tool that fillsthis gap. The Hamilton C Shell is acollection of programs that takes advantage of OS/2 features to create afaster, more powerful environment forserious OS/2. users. The Hamilton CShell efficiently uses OS/2 to implement a superset of the C shell environment used in the Berkeley flavor ofUnix. The Shell supports a powerfulscript language borrowing C's con-structs.CShell for OS/2The Hamilton C Shell is no t a quickport of a Unix shell from another system. The Shell was created from scratch,implemented with modem compiler technology, and designed to fully take advantage of the powerful OS/2 architecture, including HPFS (high-performanceScott is an independent software con-sultant specializing in systems and ap-plications programming under ViliS,Unix, DOS, and the Macintosh. He canbe reached at R.R. 3, Box 3471;Susquehanna, PA 18847.Dr. Dobb'sjournal,january 1991

    Examining theHamilton CShellUnix power for OS/2

    Scott Richmanfile system), long filenames, and threads.Additionally, the Shell supports largecommand lines and pipes (up to 64K)and includes faster and more powerfulutilities than those suppl ied with OS/2.This is more than Unix - this is a pow-erful requirement for development under OS/2. The ability to execute C shellssimultaneously in different Presentation Manager (PM) text windows converts your PC into a flexible workstation.The Hamilton C Shell comes withmany programs and shell scripts. Toinstall the Shell, you simply copy thefiles to their new home, and modifyyour CONFIG.SYS. The Shell program,CSH.EXE, can be executed in a textwindow of the PM or as a non-PMcharacter-mode application.ScriptsScripts allow you to program the manycommands and features with full sup-port for complex logic, looping, nestedcontrol statements, and symbols. Scriptsare composed of C Shell commands,OS/2 programs, and comments prefixed by the pound character (#).This combination can produce potent applications. Scripts can be composed and tested interactively at thecommand level or typed into files andrun later. The Shell assumes that fileswith extensions of .CSH are C Shellscript files. Scripts can read user inputand can be used recursively.For example, Listing One (page 106)presents CTL_T.CSH, a script to send aCtrl-T to COM1: every 400 seconds. It'suseful when logged onto a busy terminal server that impatiently bumps youoff when there's no activity. Invokingthis sCript, using ctLt &, will execute it

    in the background and the server willbe kept busy.Supporting ProceduresScript programmers can create C Shellprocedures, which are more like functions: They accept a parameter list an dreturn a value. These procedures arecompiled into C Shell memory and arethen executed as new shell commands.Procedures can greatly extend thepower and flexibility of your environment.As an example, consider ZCW.CSH(Listing Two, page 106), which is usedto build a C++ PM program. ZCW.CSHdefines a procedure that receives a filename as its parameter. The script callsthe procedure at the end: The Shellreads the file once, compiles the procedure and executes the compiled codefrom that point on. In other words, thezcw procedure is now treated like another C Shell command.Listing Three (page 106) shows theglobal edit procedure ged, which canbe used to globally edit several files.For instance, you can edit all .H filesand change your last name from "Lovejoy" to "Stern," using the commandged slLovejoylSterni *.h. As with zcw,the Shell reads and compiles the procedure and executes ged as it would anyother C Shell command.VariablesUsers can create local, environmental,and C shell global variables. These symbols can contain any text representingpathnames, strings, numbers, and soon, which can be referred to by theother Shell components. Long pathnames, for instance, could be stored

    1

  • 8/8/2019 Examining the Hamilton C Shell - Scott Richman - Dr. Dobb's Journal - Jan 1991

    2/4

    EXAMIN ING ROO Min variables and used in a commandline to refer to the target location. Todefine a variable, use the set command(set a = "this is a ")' To have the Shellcalculate an expression, use @ insteadof set.

    used to format variables. There are alsoprovisions to scan strings for substrings,concatenate variables, and return stringlengths.The Shell is also flexible in treatingsymbols as numbers and will allowcomplicated arithmetic calculations. TheShell handles integer and floating-pointarithmetic and supports C-like calculations, evaluations and expressions, including switch and case. Variables canbe tested for patterns using the Unixpattern-matching expressions.

    Additionally, variables can be arrayswith full support for C-style subscripting of the elements. The Shell makes iteasy to access the words which makeup a variable. The Shell supplies manyinternal variable functions to test andmanipulate the text within a symbol.The prinif function, for example, is Taking CommandCommand Description

    ! Inserts the first argument(or word) of the last line.

    ! Inserts all the argumentsof the last line.

    ! ! Inserts the previousline.

    Table 1: History recall commands

    The Shell has full command history. Itremembers previous command lines,which can be recalled through manydifferent methods. Besides using theup and down arrow keys to recall pastlines, you can recall a previous command line (or specific parts of it) bycommand sequence number, or youcan recall the last command which contained a specific string. Groups of command lines can be saved into a text fileand later read back into another ses-

    Utility

    Cut

    Oiff

    Strings

    xd

    More

    Ls

    VniqFgrep and grep

    Tail

    Sed

    DescriptionOutputs specific parts of each line of its input, and allows you tospecify the character positions and/or the field numbers to include.Compares files or directories, and can be instructed to ignore caseand spaces. Oiffcan recursively compare the contents of two directories. You can also define the minimum match length to insist on.Searches binary files and displays the ASCII strings found withinthem. Strings is quite handy for finding the strings embedded withina program or database.Dumps the contents of its input to stdout. This wonderful dump utilitycan display its input by bytes, words, long words, or floating-pointvalues. xd s fluent in decimal, hex, oct, and even other user-suppliedradixes. xd can be told the offsets at which to begin (and end) itsdump.Flexible full-screen file browser. More will scroll up and down, andsearch for text and line numbers. It can also format lines with octaland hex values. C programmers will appreciate the feature of displaying the \n\r escape sequences.The ultimate DIR program that specifies types of files and displays fileinformation in many different sorted orders. Ls can also displayfile-size totals. The program will, if told, recursively search the directory structure.Displays the duplicate or nonduplicate lines found in a given file.Searches files (or standard input) for specific occurrences of text.grep works with regular expressions which can help find approximated text strings.Shows the end of a file. If, however, the file is growing (anotherprocess or thread is expanding it), it can continue to show the growingfile. I find tail indispensable for logging downloads while I am free towork in another window.A stream editor -a ilter which outputs an edited version of its input.Sed will replace strings, convert characters, delete text and inserttext. Sedwill work by ranges of line numbers or regular expressions.

    Table 3: My favorite CShell utilities2

    sion. The saved command lines canbe edited by your favorite text editorand then submitted to the Shell as ascript. The Berkeley history mechanismsupplies many nifty ways to access partsof previous command lines. When acommand line contains /$, the Shellinserts the last word Cargument) of theprevious command line: Repeated sequences of commands to the same file(such as edit, compile, link and print)are executed faster and with fewer typos because the argument is never retyped. Some of the other history-recallcommands are shown in Table 1.The Shell lets you define aliases,which allow you to abbreviate or rename any command. Complicated command lines are much easier to workwith when they are defined by an alias.Once an alias is defined, it can be usedas another command.Because the C Shell furnishes manyways to group commands together onthe same command line, the Enter keyhas much more power than under conventional PC systems. Command linesending with an ampersand (& ) will beexecuted in the background. The PScommand will show the currently active processes and threads created bythe Shell and their command lines, whilethe Kill command can terminate anyjob shown by PS, making it easy tomanage a multithreaded system. Onmy wish list of future enhancements,however, is a feature that will displayand manipulate the priority of a thread.File and Command AccessibilityThe Shell controls command-name parsing through efficient hashing techniquesand sophisticated OS/2 features. Filenames are expanded within the command line with greater speed and flexibility than under OS/2. For example,when you press the Alt/Ctrl key combination, the Shell will complete a partially typed me or command name in thecurrent command line. These featuressave much time and ensure more accuracy by reducing unnecessary typing.C Shell supports full Unix filenamewildcarding, to provide a very flexiblemeans of describing groups of files.Subdirectories can also be wildcarded.The asterisk C*) and question mark (?)can represent any character except thecolon (:) and backslash (\). However,the period between the filename andits extension is no longer sacred. Awildcard expression of ' [ch] will translate into all files with either .C or .Hextensions. Square brackets declare alist of characters which can match onecharacter. If the first character withinthe square bracket list is the escapecharacterC), the list will defme all charac-

    Dr. Dobb'sjournal,january 1991

  • 8/8/2019 Examining the Hamilton C Shell - Scott Richman - Dr. Dobb's Journal - Jan 1991

    3/4

    ters that will no t match. These character lists may include ranges of characters: [A-Z] [0-9] will match any twocharacters starting with on e alphabeticand ending with on e digit.The Shell also has built-in file teststo determine file type. The commandsshown in Example 1, for instance, willprint the attributes of the file whosename is stored in the variable a. Also,the Shell can be directed to parse fullfilenames into their component parts,an d programming is no t needed to edit

    the extension ou t of a filename. Forexample, if we set the variable a to"dirl \dir1\file.ext" the Shell will interpret the filenames according to the listshown in Table 2.

    The Shell features a directory-stackmechanism comprised of the commandspushd, popd, and rotd. pushd is theCD command with memory. It will remember the current directory (by placing it on the directory stack) and thenchange to a new directory. popd willreturn to the directory at the top of thestack, and rotd will rotate the order ofthe directories saved. Jumping aroundfrom directory to directory is a snap,especially when you use wildcards todeclare the directory to push.RedirectionThe Shell supports full I/O redirectionof any of its components and allowsyou to build ne w commands from theoutput of othercommands on the samecommand line. As an example, tobrowse the unknown .C or .H files thatcontain the string VIO, invoke the command: more 'grep -I WO *.[hcj'The command line within the singlequotes is executed first, and its outputis then inserted into its place. So, monisarguments are the output of grep.

    The command line in Example 2,which finds all duplicate filenames onthe current disk, demonstrates how powerful a simple shell command can be.Example 2 starts by creating a list of allthe full pathnames of every file usingthe -r (recursive) option of Is. The :gtmeans globally trim each pathnamedown to just the tail (no drive: \dir\ \ \) .The foreach loop writes each name ou tto the pipe, one pe r line. All lines aresorted alphabetically and the uniq -dcommand outputs just the duplicates.Within moments, the current drive isscanned for all files with the same name.Supplied UtilitiesThe Hamilton C Shell product comeschock-full of many wonderful utilityprograms. All utilities have the samehomogeneous feel, a quality lackingin other software packages. Also, allHamilton supplied programs will dis-Dr. Dobb'sjournal,january 1991

    p ay help when invoked with the -h Imy ten favorites and described themswitch. Because there are so many utili- in Table 3. Table 4 lists other utilitiesties included in the package, I selected found in the package.Expression Description C Shell result$a:h (head) Directory \dir1\dir2$a:r (root) Path w/o .Ext \dir1 \dir2\fil e$a:t (tail) File name file.ext$a:e (ext.) extension w/o . ext$a:f (fullpath) expanded file name d:\top\dir1\dir2\file.ext

    Table 2: Parsing filenames into their component partsif ( -d $a) echo $a is a directoryif ( -H $a) echo $a is hiddenif ( -R $a) echo $a is ReadOnlyif ( -8 $a) echo $a is 8ystemFileif ( -e $a) echo $a existsif ( -x $a) echo $a is executableif ( -z $a) echo $a zero length

    Example 1: Commands toprint the attributes ofa specified fileforeach i ( ' Is - r \ ' :gt) echo $i; end I sort I uniq -d.

    Example 2: Command to find all duplicate file names on the curren t diskUtilitychmodmarkexepwdmkdirsumtardtsetrowspatchlnkduvilabelnewerolderteetrwcsplittabscatheadrmdircp&mv

    rm

    DescriptionChange mode bits on files (not directories)Set OS/2 application type bitsPrint the current working directoriesMake directoriesChecksum the contents of a fileRead/write Unix tape archive format filesPrint the date and timeSet height of current windowPatch "the linker bug"List disk usage statisticsList volume labelsRead/write the volume labelTest whether file1 is newer than all the othersTest whether file1 is older than all the othersCopy Stdin to Stdout and to each file specifiedTranslate characters filterCount words (and lines and characters)Split a large file into chunksExpand/unexpand tabsConcatenate files to StdoutCopy first part of file to outputRemove directoriesCopy (or move) files or directories. These two programs can force read-onlyfiles to be overwritten. They can ask before acting on each file and can logthe action. Both will merge subdirectories.Remove files or directories. rm can force read-only files to be overwritten.rm can ask before acting on each file and can log the action. rm canrecursively remove non-empty directories. (System files or hidden files ordirectories can be removed.)

    Table 4: Hamilton utility programs3

  • 8/8/2019 Examining the Hamilton C Shell - Scott Richman - Dr. Dobb's Journal - Jan 1991

    4/4

    EXAM IN ING ROO MFinal AssessmentOf course, no product is without itsblemishes. Although it improves witheach update, the documentation is theweakest part of this otherwise fine product. The documentation is written fora highly technical user who understandsOS/2 and Unix. Users new to Unix willneed to read other documents (see Bibliography). The sparseness of completeshell scripts makes it hard for a noviceC Shell user to appreciate the manywonderful features of this product. Unix.can be cryptic and unfriendly, but theShell's qwesome power makes it worththe effort of learning.While the C Shell is a text powerhouse, database capabilities wouldmake this product more helpful forbusiness-oriented tasks. More powerful record I/O procedures and structures for full record handling wouldhelp. If C Shell could integrate an ISAMengine, C Shell applications could beused to solve complex business andscientific problems.A screen-capturing feature and internal date functions would be greatlyappreciated. The Macintosh MPW commando facility of dialoguing a shell command would help users build complexcommands without the aid of manuals.While C Shell works fine in a PMtext window, inevitably it will evolveinto a full graphics PM application. Sucha version should embody the programming strengths of HyperCard. Controlsand gadgets should invoke scripts, andprogrammable dialogues could facilitate PM applications creation.BibliographyAnderson, Gail and Paul Anderson. Unix:C Shell Field Guide. Englewood Cliffs,N.J.: Prentice Hall, 1986.Muster, John and Peter Birns. Unix:Power Utilities. Portland, Ore.: MIS Press,1989.The Waite Group. Unix: Primer Plus.2nd ed. Carmel, Ind.: Howard Sams,1990,

    DDJ

    Entire contents copyright e 1991 by M&T Publishing. Inc., unlessorherwise noted on specific articles. AU rigilis reserved.MP .s Th.AuditBureau

    Reprinted with permission of Dr.Dobb's Journal, 1991

    4

    Listing Onef CTL_T.CSHwhile (1)echo -n "x14 > coml:sleep 400en d f while

    Listing Two

    It endless* end control t to coml: Zzz fo r 400 seconds

    f Procedure zew builds Zortech c++ and creates a PM program,proc zew (name)' param namezt c -w -c $name.cpp corrpile ($name is paramname) t we tes t name.obj fo r eistance,i f (-e $name.obj) then t go t valid ob j f i le to linklink $name, /al ign:16, NUL, os2+d: \oz\cp\srzpm.lib, $namerm $name.obj remove th e ob jend f ifend t proczcw $argv t now here's th e invocation of my proc defined above.

    Listing Threeproc ged(edt_str, files)local ilocal nforeach i (Sfiles)

    @ n = concat(Si:r,".bak")cp -1 $i:f $n:fsed "$edt st r" < $n:f > $i : fend f foreach i -end end ged proc ()

    f 2 pararnst local variables usedf loop thru th e f i1esf save a backup (: r is root name) copy i t (: f is ful l name)I edit from new to i

    End Usting One

    End Usting Two

    " ..much more powerful than CMD.EXE ..blindingly fast ..we have a winner ..a much-needed and well-done product."

    - Personal Workstation MagazineThe finest OS/2 command processor andutilities available. Ideal for anyone facedwith daily tasks launching applications orbrowsing or maintaining the file system.Created explicitly for OS/2. RunsinaPMtextwindow. Extensivelymulti-threaded.Full-screen command line editing: Recalland edit previous commands with the arrowand function keys. Cut and paste anywhere.Filename and command completion.Powerful scripting abilities: Excels atcomplex, tedious or repetitive projects.Faithfully recreates the entire C shelllanguage as described in the Berkeley 4.3UNIX Programmer's Manual.

    Virtually every important utility you willever need: ca t , chmod, cIs , cp, cut ,d i f f , du , fgrep, grep, head, I s , k i l l ,more, mv, popd, ps, pushd, pwd, rm, sed,s l eep , s p l i t , s t r ing s , t abs , t a i l , t a r ,t ee , t ime, touch, t r , uniq , vol , wait ,wc and almost a hundred other commands.Suppo rts HPFS and long filenames.Easily saves an hour a day. Easy to installandeasy to use. Unlimited support.$350.00. Unconditional satisfactionguarantee. MasterCard & Visa accepted.($365.00 Canada/Mexico; $395.00 elsewhere.)

    Hamilton Laboratories13 Old Farm Road, Wayland, MA 01778-3117, U.S.A.Phone 508-358-5715 FAX 508-358-1113 BIX hamilton