Полезная информация

UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 45.4 Fun with #! Chapter 45
Shell Programming for the Initiated
Next: 45.6 Making Sure Your Script Runs with Bourne Shell, Without #!
 

45.5 A File That Shows Itself... and What #! Does

If your UNIX understands (44.4) executable files that start with #!, you can use this nice trick to make executable files that display themselves (or part of themselves). I used this to make a program named help on a system that didn't have any online help. A program like cat (25.2) isn't what you want because it'll display the #! line as well as the message. Watch what happens:

% cat help
#!/bin/cat
For help with UNIX, call the ACS Consulting Hotline at 555-1212.

man command               shows the manual for a command
   ...
% chmod +x help
% help
#!/bin/cat
For help with UNIX, call the ACS Consulting Hotline at 555-1212.

man command               shows the manual for a command
   ...

The trick is to invoke an interpreter that shows all the lines except the line starting with #!. For example, this file uses sed (34.24) and its d command to ignore ("delete") the first line:

% cat help
#!/bin/sed 1d
For help with UNIX, call the ACS Consulting Hotline at 555-1212.

man command               shows the manual for a command
   ...
% help
For help with UNIX, call the ACS Consulting Hotline at 555-1212.

man command               shows the manual for a command
   ...

For longer files, try using more +2 (25.3); this file will show itself screenful-by-screenful, starting at line 2:

% cat help
#!/usr/ucb/more +2
For help with UNIX, call the ACS Consulting Hotline at 555-1212.

man command               shows the manual for a command
   ...

You have to give the absolute pathname to the interpreter because the kernel doesn't use your search path (8.7). The kernel can pass just one argument to the interpreter. More than one argument probably won't work. In the next example, I try to pass two arguments to grep-but the kernel passes the whole string -v # as just one argument. That confuses grep, which complains about every character from the space on:

% cat help
#!/bin/grep -v #
For help with UNIX, call the ACS Consulting Hotline at 555-1212.

man command               shows the manual for a command
   ...
% help
grep: illegal option --
grep: illegal option -- ^
grep: illegal option -- #
Usage: grep -hblcnsvi pattern file . . .

(Remember, there's no shell interpreting the arguments here. The kernel does it.)

- JP


Previous: 45.4 Fun with #! UNIX Power ToolsNext: 45.6 Making Sure Your Script Runs with Bourne Shell, Without #!
45.4 Fun with #! Book Index45.6 Making Sure Your Script Runs with Bourne Shell, Without #!

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System