EXAMINING ROO M

Examining the Hamilton Shell

Unix power for OS/2

Scott Richman

tarting OS/2 for the first time was, file system), long filenames, and threads. in the background and the server will for me, like unlocking a Ferarri, Additionally, the Shell supports large be kept busy. sitting behind its wheel and ­ command lines and pipes (up to 64K) ing a Yugo's dash. What a disap­ and includes faster and more powerful Supporting Procedures pointment. Sure, the engine and utilities than those supplied with OS/2. programmers can create suspensionS were first rate, but the con­ This is more than Unix - this is a pow­ procedures, which are more like func­ trols were minimal, the clutch was stiff, erful requirement for development un­ tions: They accept a parameter list and and the pedals were nonresponsive! der OS/2. The ability to execute C shells return a value. These procedures are OS/2 comes with great stuff, but CMD simultaneously in different Presenta­ compiled into C Shell memory and are .EXE, the default command-line pro­ tion Manager (PM) text windows con­ then executed as new shell commands. cessor, is poor compared to the pow­ verts your PC into a flexible workstation. Procedures can greatly extend the erfuloperating system beneath. CMD.EXE The comes with power and flexibility of your environ­ appears to be a port of the MS-DOS many programs and shell scripts. To ment. COMMAND.COM and lacks the major install the Shell, you simply copy the As an example, consider ZCW.CSH features of a serious front end. files to their new home, and modify (Listing Two, page 106), which is used Fortunately, there's a tool that fills your CONFIG.SYS. The Shell program, to build a C++ PM program. ZCW.CSH this gap. The Hamilton C Shell is a CSH.EXE, can be executed in a text defines a procedure that receives a file­ collection of programs that takes ad­ window of the PM or as a non-PM name as its parameter. The script calls vantage of OS/2 features to create a character-mode application. the procedure at the end: The Shell faster, more powerful environment for reads the file once, compiles the proce­ serious OS/2. users. The Hamilton C Scripts dure and executes the compiled code Shell efficiently uses OS/2 to imple­ Scripts allow you to program the many from that point on. In other words, the ment a superset of the C shell environ­ commands and features with full sup­ zcw procedure is now treated like an­ ment used in the Berkeley flavor of port for complex logic, looping, nested other C Shell command. Unix. The Shell supports a powerful control statements, and symbols. Scripts Listing Three (page 106) shows the script language borrowing C's con­ are composed of C Shell commands, global edit procedure ged, which can structs. OS/2 programs, and comments pre­ be used to globally edit several files. fixed by the pound character (#). For instance, you can edit all .H files C Shell for OS/2 This combination can produce po­ and change your last name from "Love­ The Hamilton C Shell is not a quick tent applications. Scripts can be com­ joy" to "Stern," using the command port of a from another sys­ posed and tested interactively at the ged slLovejoylSterni *.h. As with zcw, tem. The Shell was created from scratch, command level or typed into files and the Shell reads and compiles the proce­ implemented with modem tech­ run later. The Shell assumes that files dure and executes ged as it would any nology, and designed to fully take ad­ with extensions of .CSH are C Shell other C Shell command. vantage of the powerful OS/2 architec­ script files. Scripts can read user input ture, including HPFS (high-performance and can be used recursively. Variables For example, Listing One (page 106) Users can create local, environmental, Scott is an independent software con­ presents CTL_T.CSH, a script to send a and C shell global variables. These sym­ sultant specializing in systems and ap­ Ctrl-T to COM1: every 400 seconds. It's bols can contain any text representing plications programming under ViliS, useful when logged onto a busy termi­ pathnames, strings, numbers, and so Unix, DOS, and the Macintosh. He can nal server that impatiently bumps you on, which can be referred to by the be reached at R.R. 3, Box 3471; off when there's no activity. Invoking other Shell components. Long ­ Susquehanna, PA 18847. this sCript, using ctLt &, will execute it names, for instance, could be stored

Dr. Dobb'sjournal,january 1991 1 EXAMINING ROO M in variables and used in a command used to format variables. There are also sion. The saved command lines can line to refer to the target location. To provisions to scan strings for substrings, be edited by your favorite text editor define a variable, use the set command concatenate variables, and return string and then submitted to the Shell as a (set a = "this is a ")' To have the Shell lengths. script. The Berkeley history mechanism calculate an expression, use @ instead The Shell is also flexible in treating supplies many nifty ways to access parts of set. symbols as numbers and will allow of previous command lines. When a Additionally, variables can be arrays complicated arithmetic calculations. The command line contains /$, the Shell with full support for C-style subscript­ Shell handles integer and floating-point inserts the last word Cargument) of the ing of the elements. The Shell makes it arithmetic and supports C-like calcula­ previous command line: Repeated se­ easy to access the words which make tions, evaluations and expressions, in­ quences of commands to the same file up a variable. The Shell supplies many cluding switch and case. Variables can (such as edit, compile, link and print) internal variable functions to and be tested for patterns using the Unix are executed faster and with fewer ty­ manipulate the text within a symbol. pattern-matching expressions. pos because the argument is never re­ The prinif function, for example, is typed. Some of the other history-recall Taking Command commands are shown in Table 1. Command Description The Shell has full command history. It The Shell lets you define aliases, remembers previous command lines, which allow you to abbreviate or re­ which can be recalled through many name any command. Complicated com­ ! • Inserts the first argument different methods. Besides using the mand lines are much easier to work (or word) of the last line. up and down arrow keys to recall past with when they are defined by an . ! • Inserts all the arguments lines, you can recall a previous com­ Once an alias is defined, it can be used of the last line. mand line (or specific parts of it) by as another command. command sequence number, or you Because the C Shell furnishes many ! ! Inserts the previous ways to group commands together on line. can recall the last command which con­ tained a specific string. Groups of com­ the same command line, the Enter key mand lines can be saved into a text file has much more power than under con­ Table 1: History recall commands and later read back into another ses- ventional PC systems. Command lines ending with an ampersand (&) will be Utility Description executed in the background. The PS command will show the currently ac­ tive processes and threads created by Cut Outputs specific parts of each line of its input, and allows you to the Shell and their command lines, while specify the character positions and/or the field numbers to include. the Kill command can terminate any job shown by PS, making it easy to Oiff Compares files or directories, and can be instructed to ignore case and spaces. Oiffcan recursively compare the contents of two directo­ manage a multithreaded system. On ries. You can also define the minimum match length to insist on. my list of future enhancements, however, is a feature that will display Strings Searches binary files and displays the ASCII strings found within and manipulate the priority of a . them. Strings is quite handy for finding the strings embedded within a program or database. File and Command Accessibility xd Dumps the contents of its input to stdout. This wonderful dump utility The Shell controls command-name pars­ can display its input by bytes, words, long words, or floating-point ing through efficient hashing techniques values. xd is fluent in decimal, hex, oct, and even other user-supplied and sophisticated OS/2 features. File­ radixes. xd can be told the offsets at which to begin (and end) its names are expanded within the com­ dump. mand line with greater speed and flexi­ More Flexible full-screen file browser. More will scroll up and down, and bility than under OS/2. For example, search for text and line numbers. It can also format lines with octal when you press the Alt/Ctrl key combi­ and hex values. C programmers will appreciate the feature of display­ nation, the Shell will complete a par­ ing the \n\r escape sequences. tially typed me or command name in the Ls The ultimate DIR program that specifies types of files and displays file current command line. These features information in many different sorted orders. Ls can also display save much time and ensure more accu­ file-size totals. The program will, if told, recursively search the direc­ racy by reducing unnecessary typing. tory structure. C Shell supports full Unix filename wildcarding, to provide a very flexible Vniq Displays the duplicate or nonduplicate lines found in a given file. means of describing groups of files. Subdirectories can also be wildcarded. Fgrep and Searches files (or standard input) for specific occurrences of text. grep works with regular expressions which can help find approxi­ The asterisk C*) and question mark (?) mated text strings. can represent any character except the colon (:) and backslash (\). However, Tail Shows the end of a file. If, however, the file is growing (another the period between the filename and or thread is expanding it), it can continue to show the growing its extension is no longer sacred. A file. I find tail indispensable for logging downloads while I am free to wildcard expression of' .[ch] will trans­ work in another window. late into all files with either .C or .H Sed A stream editor -a filter which outputs an edited version of its input. extensions. Square brackets declare a Sed will replace strings, convert characters, delete text and insert list of characters which can match one text. Sed will work by ranges of line numbers or regular expressions. character. If the first character within the square bracket list is the escape Table 3: My favorite C Shell utilities character C), the list will defme all charac-

2 Dr. Dobb'sjournal,january 1991 ters that will not match. These charac­ p ay help when invoked with the -h I my ten favorites and described them ter lists may include ranges of charac­ switch. Because there are so many utili- in Table 3. Table 4 lists other utilities ters: [A-Z] [0-9] will match any two ties included in the package, I selected found in the package. characters starting with one alphabetic and ending with one digit. Expression Description C Shell result The Shell also has built-in file tests to determine file type. The commands $a:h (head) Directory \dir1\dir2 shown in Example 1, for instance, will $a:r (root) Path w/o .Ext \dir1 \dir2\file print the attributes of the file whose name is stored in the variable a. Also, $a:t (tail) File name file.ext the Shell can be directed to parse full $a:e (ext.) extension w/o . ext filenames into their component parts, $a:f (fullpath) expanded file name d:\top\dir1\dir2\file.ext and programming is not needed to edit the extension out of a filename. For Table 2: filenames into their component parts example, if we set the variable a to "dirl \dir1\file.ext" the Shell will inter­ pret the filenames according to the list if ( -d $a) $a is a directory if ( -H $a) echo $a is hidden shown in Table 2. if ( -R $a) echo $a is ReadOnly The Shell features a directory-stack if ( -8 $a) echo $a is 8ystemFile mechanism comprised of the commands if ( -e $a) echo $a exists pushd, popd, and rotd. pushd is the if ( -x $a) echo $a is executable if ( -z $a) echo $a zero length CD command with memory. It will re­ member the current directory (by plac­ ing it on the directory stack) and then Example 1: Commands to print the attributes ofa specified file change to a new directory. popd will return to the directory at the top of the stack, and rotd will rotate the order of foreach i ('Is -r \' :gt) echo $i; end I sort I uniq -d. the directories saved. Jumping around from directory to directory is a snap, Example 2: Command to find all duplicate file names on the current disk especially when you use wildcards to declare the directory to push. Utility Description The Shell supports full I/O redirection chmod Change mode bits on files (not directories) of any of its components and allows markexe Set OS/2 application type bits you to build new commands from the pwd Print the current working directories output of other commands on the same command line. As an example, to mkdir Make directories browse the unknown .C or .H files that sum Checksum the contents of a file contain the string VIO, invoke the com­ tar Read/write Unix tape archive format files mand: more 'grep -I WO *.[hcj' dt Print the date and time The command line within the single quotes is executed first, and its output setrows Set height of current window is then inserted into its place. So, monis patchlnk Patch "the linker bug" arguments are the output of grep. du List disk usage statistics The command line in Example 2, vi List volume labels which finds all duplicate filenames on the current disk, demonstrates how pow­ label Read/write the volume label erful a simple shell command can be. newer Test whether file1 is newer than all the others Example 2 starts by creating a list of all older Test whether file1 is older than all the others the full pathnames of every file using tee Copy Stdin to Stdout and to each file specified the -r (recursive) option of Is. The :gt means globally trim each pathname tr Translate characters filter down to just the tail (no drive: \dir\ \ \). wc Count words (and lines and characters) The foreach loop writes each name out split Split a large file into chunks to the pipe, one per line. All lines are tabs Expand/unexpand tabs sorted alphabetically and the uniq -d cat command outputs just the duplicates. Concatenate files to Stdout Within moments, the current drive is head Copy first part of file to output scanned for all files with the same name. rmdir Remove directories cp&mv Copy (or move) files or directories. These two programs can force read-only Supplied Utilities files to be overwritten. They can ask before acting on each file and can log The Hamilton C Shell product comes the action. Both will merge subdirectories. chock-full of many wonderful utility Remove files or directories. rm can force read-only files to be overwritten. programs. All utilities have the same rm can ask before acting on each file and can log the action. rm can homogeneous feel, a quality lacking recursively remove non-empty directories. (System files or hidden files or in other software packages. Also, all directories can be removed.) Hamilton supplied programs will dis- Table 4: Hamilton utility programs

Dr. Dobb'sjournal,january 1991 3 EXAMINING ROO M

Final Assessment Of course, no product is without its Listing One blemishes. Although it improves with f CTL_T.CSH each update, the documentation is the while (1) It endless weakest part of this otherwise fine prod­ echo -n "x14 > coml: * send control t to coml: sleep 400 • Zzz for 400 seconds uct. The documentation is written for end f while a highly technical user who understands OS/2 and Unix. Users new to Unix will need to read other documents (see Bib­ End Usting One liography). The sparseness of complete shell scripts makes it hard for a novice Listing Two C Shell user to appreciate the many f Procedure zew builds Zortech c++ and creates a PM program, proc zew (name)' • param name wonderful features of this product. Unix ztc -w -c $name.cpp • corrpile ($name is param . can be cryptic and unfriendly, but the name) t we test name.obj for eistance, Shell's qwesome power makes it worth if (-e $name.obj) then t got valid obj file to link link $name, /align: 16, NUL, os2+d: \oz\cp\srzpm.lib, $name the effort of learning. rm $name.obj • remove the obj While the C Shell is a text power­ end f if house, database capabilities would end t proc make this product more helpful for zcw $argv t now here's the invocation of my proc defined above. business-oriented tasks. More power­ ful record I/O procedures and struc­ End Usting Two tures for full record handling would help. If C Shell could integrate an ISAM Listing Three engine, C Shell applications could be proc ged(edt_str, files) f 2 pararns local i t local variables used used to solve complex business and local n scientific problems. foreach i (Sfiles) f loop thru the f i1es @ n = concat(Si:r,".bak") f save a backup (: r is root name) A screen-capturing feature and inter­ cp -1 $i:f $n:f • copy it (: f is full name) sed "$edt str" < $n:f > $i:f I edit from new to i nal date functions would be greatly end f foreach i - appreciated. The Macintosh MPW com­ end • end ged proc () mando facility of dialoguing a shell com­ mand would help users build complex commands without the aid of manuals. While C Shell works fine in a PM text window, inevitably it will evolve into a full graphics PM application. Such a version should embody the program­ ming strengths of HyperCard. Controls and gadgets should invoke scripts, and programmable dialogues could facili­ tate PM applications creation.

Bibliography Anderson, Gail and Paul Anderson. Unix: " ... much more powerful than CMD.EXE ... blindingly fast ... C Shell Field Guide. Englewood Cliffs, we have a winner... a much-needed and well-done product." N.J.: Prentice Hall, 1986. - Personal Workstation Magazine Muster, John and Peter Birns. Unix: Power Utilities. Portland, Ore.: MIS Press, The finest OS/2 command processor and Virtually every important utility you will 1989. utilities available. Ideal for anyone faced ever need: cat, chmod, cIs, cp, cut, The Waite Group. Unix: Primer Plus. with daily tasks launching applications or diff, du, fgrep, grep, head, Is, kill, 2nd ed. Carmel, Ind.: Howard Sams, browsing or maintaining the file system. more, mv, popd, ps, pushd, pwd, rm, sed, 1990, Created explicitly for OS/2. RunsinaPMtext sleep, split, strings, tabs, tail, tar, window. Extensivelymulti-threaded. tee, time, touch, tr, uniq, vol, wait, DDJ wc and almost a hundred other commands. Full-screen command line editing: Recall and edit previous commands with the arrow Supports HPFS and long filenames. Entire contents copyright e 1991 by M&T Publishing. Inc., unless orherwise noted on specific articles. AU rigilis reserved. and function keys. Cut and paste anywhere. Filename and command completion. Easily saves an hour a day. Easy to install Th. and easy to use. Unlimited support. MP Audit Powerful scripting abilities: Excels at Bureau .s complex, tedious or repetitive projects. Faithfully recreates the entire C shell $350.00. Unconditional satisfaction language as described in the Berkeley 4.3 guarantee. MasterCard & Visa accepted. UNIX® Programmer's Manual. ($365.00 Canada/Mexico; $395.00 elsewhere.) Hamilton Laboratories Reprinted with permission of Dr. 13 Old Farm Road, Wayland, MA 01778-3117, U.S.A. Dobb's Journal, 1991 Phone 508-358-5715 • FAX 508-358-1113 • BIX hamilton

4