1.5 Anyone Can Program the ShellOne of the really wonderful things about the shell is that it doesn't just read and execute the commands you type at a prompt. The shell is a complete programming language. The ease of shell programming is one of the real highlights of UNIX for novices. A shell program need be no more than a single complex command line saved in a file - or a series of commands. For example, let's say that you occasionally need to convert a Macintosh Microsoft Word file for use on your UNIX system. Word lets you save the file in ASCII format. But there's a catch: the Macintosh uses a carriage return ( ASCII character 015 ( 51.3 ) ) to mark the end of each line, while UNIX uses a linefeed (ASCII 012). As a result, with UNIX, the file looks like one long paragraph, with no end in sight. That's easy to fix: the UNIX tr ( 35.11 ) command can convert every occurrence of one character in a file to another:
% But you're a novice, and you don't want to remember this particular piece of magic. Fine. Save the first part of this command line in a file called mac2UNIX in your personal bin directory ( 4.2 ) :
tr '\015' '\012' Make the file executable with chmod ( 22.7 ) :
% Now you can say:
% But say, why settle for that? What if you want to convert a bunch of files at once? Easy. The shell includes a general way of referring to arguments passed to a script, and a number of looping constructs. The script:
will convert any number of files with one command, replacing each original with the converted version:
% As you become more familiar with UNIX, it quickly becomes apparent that doing just a little homework can save hours of tedium. This script incorporates only two simple programming constructs: the for loop and variable substitution ( 6.8 , 6.1 ) . As a new user, with no programming experience, I learned these two constructs by example: I saved a skeleton for loop in a file and simply filled in the blanks with whatever commands I wanted to repeat. Simple shell programs like this did more for my feeling that computers could automate my work than anything since my first introduction to word processing. It made real sense of the line, "Let the computer do the dirty work." In short, UNIX is sometimes difficult because it is so rich and complex. The user who doesn't want to learn the complexity doesn't have to - the basic housekeeping commands are as simple as MS-DOS on the IBM PC. But the user who wants to take the time to investigate the possibilities can uncover a wealth of useful tools. - |
|