5.13. Shell Programs (Scripts)Any series of shell commands may be stored inside a regular text file for later execution. A file that contains shell commands is called a script. Before you can run a script, you must give it execute permission by using the chmod utility. Then, to run it, you only need to type its name. Scripts are useful for storing commonly used sequences of commands, and range in complexity from simple one-liners to full blown programs. The control structures supported by the languages built into the shells are sufficiently powerful to enable scripts to perform a wide variety of tasks. System administrators find scripts particularly useful for automating repetitive administrative tasks such as warning users when their disk usage goes beyond a certain limit. When a script is run, the system determines which shell the script was written for, and then executes the shell using the script as its standard input. The system decides which shell the script is written for by examining the first line of the script. Here are the rules that it uses:
If a # appears on any other line apart from the first line, all characters up to the end of that line are treated as a comment. Scripts should be liberally commented in the interests of maintainability. When you write your own scripts, I recommend that you use the #! form to specify which shell the script is designed for, as it's completely unambiguous and doesn't require the reader to be aware of the default rules (especially since the default is different for UNIX and Linux). Here is an example that illustrates the construction and execution of two scripts, one for the C shell, and the other for the Korn shell: $ cat > script.csh ...create the C shell script. #!/bin/csh # This is a sample C shell script. The ".csh" and ".ksh" extensions of my scripts are used only for clarity; scripts can be called anything at all, and don't even need an extension. Note the usage of "\c" and "-n" in the above examples of the echo command. Different versions of "/bin/echo" use one or the other to omit the newline. It may also depend on the shell being used. If the shell has a built-in echo function, then the specifics of "/bin/echo" won't matter. You'll want to experiment with your particular shell and echo combination; it isn't quite as simple as I implied in the above comments. |